[英]Access parent variable from child component template
我有两个类, Secure
和Client
。 我的Secure
类是Client
的父类。
想法是,当类扩展Secure
,构造函数将检查身份验证,如果用户未通过身份验证,则会重定向到登录页面。 该类如下所示:
export class Secure {
protected user: User;
constructor(public router: Router, public userHandler: UserHandler) {
userHandler.checkAuthentication(this);
}
isLoggedIn(message: string, isLoggedIn: boolean) {
if(!isLoggedIn){
this.router.navigate(['/']);
}
}
getUser(): User{
return this.user;
}
}
我的孩子班级看起来像这样:
export class ClientsComponent extends Secure{
client: Client = new Client();
clients: Array<Client>;
constructor(public router: Router, public userHandler: UserHandler, public clientService: ClientService) {
super(router, userHandler);
}
ngOnInit() {
this.clientService.getAllUsers(this);
}
doRegister(){
this.clientService.createNewClient(this.client.email, this);
}
callbackRegisterComplete(){
this.clientService.getAllUsers(this);
}
callbackWithClients(clients:Array<Client>){
this.clients = clients;
}
}
在我的Clients
模板中,我想检查Secure
类中的用户是否具有特定角色:
<tr *ngFor="let client of clients; let i = index">
<th scope="row">{{i+1}}</th>
<td>{{client.email}}</td>
<td>{{client.userStatus}}</td>
<td *ngIf="user.isAdmin">...</td>
</tr>
但这会产生以下错误: 无法读取未定义的属性'isAdmin'
所以我的问题是:有没有办法从子类模板访问父类中的变量? 如果没有,是否有任何好的方法来解决此问题?
无需扩展,只需使用@Input()
将数据从父组件传递到子组件:
parent
模板:
<child [someData]="data"></child>
这是跨组件共享数据的最有效方法。
现在在child
您可以通过this.someData
或someData
来获取数据(如果要从模板中获取数据)。
如果您的子组件仅与其父组件严格相关,则可以使用继承。
只需从父级扩展,您将拥有父级在子级组件中拥有的所有内容。
@Component({
selector: 'task',
template: `<task-body></task-body>`,
})
export class TaskComponent{
taskType:any;
}
@Component({
selector: 'task-body',
template: `Here you can see variable from parent {{taskType}}`,
})
export class TaskBodyComponent extends TaskComponent{
//also you can use parent variable in your child component as that
variable would exist on your child
logSomething(){
console.log(this.taskType);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.