[英]Angular 2 update child component's class list from parent
I'm new to Angular 2 and I need some help with the following issue. 我是Angular 2的新手,在以下问题上我需要一些帮助。 I have a parent and a nested, child component: 我有一个父级和一个嵌套的子级组件:
// The Parent:
import { Component, ViewChild } from 'angular2/core';
import {Preloader} from 'components/preloader/preloader';
@Component({
selector: 'console',
providers: [Preloader],
directives: [Preloader],
templateUrl: 'components/console/console.html'
})
export class Console {
@ViewChild(Preloader) preloader: Preloader;
constructor(preloader: Preloader) {
this.preloader = preloader;
}
ngAfterViewInit() {
this.preloader.showConsole();
}
}
// ...and the Child
import {Component} from 'angular2/core';
@Component({
selector: 'preloader',
template: `
<div [ngClass]="style"></div>
`
})
export class Preloader {
constructor() {
this.style = {
fullscreen: true,
done: false
};
}
showConsole() {
// this is not working:
this.style.done = true;
}
}
I'd like to set both variables in style
object to true
when the parent component is fully mounted. 当父组件完全装入时,我想将style
对象中的两个变量都设置为true
。 That actually happends, but in the Preloader's template I see only fullscreen
class even after showConsole
method was called and style.done
was set to true
. 确实发生了这种情况,但是在Preloader的模板中,即使调用showConsole
方法并将style.done
设置为true
我也只能看到fullscreen
类。
console.html
template is just like this: console.html
模板如下所示:
<div class="main-window">
<preloader></preloader>
</div>
I just tested and your solution is working without any problem. 我刚刚测试过,您的解决方案可以正常工作。
But if you still say fullscreen
class remains same then you can consider below solution, 但是,如果您仍然说fullscreen
课程保持不变,则可以考虑以下解决方案,
ngAfterViewInit() {
setTimeout(()=>{
this.preloader.showConsole();
},0)
}
showConsole() {
this.style.fullscreen = false; //<<<===added.
this.style.done = true;
}
I've figured it out! 我知道了! The problem was in the communication between two components. 问题出在两个组件之间的通信中。 First of all this is how I should have pass the data in the template: 首先,这是我应该如何传递模板中的数据:
<div class="main-window">
<preloader [start]='showConsole'></preloader>
</div>
But, the most important thing, it also requires to specificate input variables in the child @Component
like this: 但是,最重要的是,它还需要在子@Component
中指定输入变量,如下所示:
@Component({
inputs: ['start'],
selector: 'preloader',
template: `<div [ngClass]="style"></div>`
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.