通过模板将数据从父级传递给子级 [英] Passing data from Parent to Child via template
本文介绍了通过模板将数据从父级传递给子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模板用户,如下所示:
<div class="容器"><h2><i class="fa fa-user"></i>{{用户名}}<p><i class="fa fa-star"></i>{{声誉}}</p>
<app-list user={{username}}"></app-list>
我的 app-list 组件如下所示:
导出类 ListComponent 实现 OnInit {@Input() 用户:字符串;构造函数(){}ngOnInit() {控制台日志(this.user);}}
用户名和声誉正确显示在页面上.然而,用户名值没有正确传递给子组件 app-list,因为它只打印出一个空字符串.
如何将用户名传递给 app-list 组件?
编辑
用户组件如下所示:
导出类 UserComponent 实现 OnInit {私人用户名:字符串;私人声誉:数量;构造函数(私有路由:ActivatedRoute,私有 apiService:ApiService){}ngOnInit() {this.route.params.subscribe((params: Params) => (this.apiService.getUser(params['username']).subscribe((response: Response) => {console.log(response.json());this.username = response.json().username;this.reputation = response.json().reputation;}, (错误) =>{如果(错误.状态 === 404){//待办事项:重定向到 404 页面}})));}}
解决方案
应该是,
<app-list [user]="username"></app-list>
I have a template user like following:
<div class="jumbotron">
<div class="container">
<h2><i class="fa fa-user"></i> {{username}}</h2>
<p><i class="fa fa-star"></i> {{reputation}}</p>
</div>
</div>
<app-list user={{username}}"></app-list>
My component for app-list looks like:
export class ListComponent implements OnInit {
@Input() user: string;
constructor() { }
ngOnInit() {
console.log(this.user);
}
}
The username and reputation is correctly shown on the page. However the username value is not passed correctly to the sub component app-list as it only print out an empty string.
How can I pass the username to the app-list component?
Edit
The user component looks like:
export class UserComponent implements OnInit {
private username: string;
private reputation: number;
constructor(private route: ActivatedRoute, private apiService: ApiService) {
}
ngOnInit() {
this.route.params.subscribe((params: Params) => (
this.apiService.getUser(params['username']).subscribe((response: Response) => {
console.log(response.json());
this.username = response.json().username;
this.reputation = response.json().reputation;
}, (error) => {
if (error.status === 404) {
// Todo: redirect to 404 page
}
}
)
));
}
}
解决方案
It should be,
<app-list [user]="username"></app-list>
这篇关于通过模板将数据从父级传递给子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文