Plunker
之间有一个小的不匹配@Input() kamers
和模板*ngIf="kamer.patient == null"
.
模板 HTML
<md-card class="chamber wit" *ngIf="kamer.patient === null">
<p *ngIf="showId">{{kamer.id}}</p>
</md-card>
<button (click)="toggleId()">Toggle</button>
成分
@Component({
selector: 'material-app',
templateUrl: 'app.component.html'
})
export class AppComponent {
kamer = {
patient: null,
id: '1'
};
showId = false;
ngOnInit() {
}
toggleId() {
this.showId = !this.showId;
}
}
更新(1) -笨蛋 (1)
Use @ViewChild
要引用子组件的函数,请使用查看子对象
- Place
@ViewChild('child') child;
在父组件中
- 在父模板中引用子函数,如下所示:
<button (click)="child.toggleId()">Toggle</button>
父组件
@Component({
selector: 'material-app',
template: `
<material-child #child></material-child>
<button (click)="child.toggleId()">Toggle</button>
`
})
export class AppComponent {
@ViewChild('child') child;
}
子模板
<md-card class="chamber wit" *ngIf="kamer.patient === null">
<p *ngIf="showId">{{kamer.id}}</p>
</md-card>
子组件
@Component({
selector: 'material-child',
templateUrl: 'app.component.html'
})
export class ChildComponent {
kamer = {
patient: null,
id: '1'
};
showId = false;
ngOnInit() {
}
toggleId() {
this.showId = !this.showId;
}
}
更新(2)-笨蛋 (2)
Use @Output()
+ EventEmitter
要扩展之前的设置以使用同级组件,您可以
- 让同级使用事件发射器
- 监听父组件中发出的事件,并调用所需的子函数
ViewChild
兄弟组件
@Component({
selector: 'material-sibling',
template: `
<button (click)="toggle.emit()">Toggle</button>
`
})
export class SiblingComponent {
@Output() toggle = new EventEmitter();
}
父组件
@Component({
selector: 'material-app',
template: `
<material-child #child></material-child>
<material-sibling (toggle)="child.toggleId()"></material-sibling>
`
})
export class AppComponent {
@ViewChild('child') child;
}
子模板
<md-card class="chamber wit" *ngIf="kamer.patient === null">
<p *ngIf="showId">{{kamer.id}}</p>
</md-card>
子组件
@Component({
selector: 'material-child',
templateUrl: 'app.component.html'
})
export class ChildComponent {
kamer = {
patient: null,
id: '1'
};
showId = false;
ngOnInit() {
}
toggleId() {
this.showId = !this.showId;
}
}