如何在单击按钮时在另一个组件内渲染该组件?
答案 0 :(得分:0)
我认为您正在寻找的是 EventEmitters 。有关文档,请参见https://angular.io/api/core/EventEmitter。
这是一个简单的代码笔来演示:https://codepen.io/devmaximilian/pen/bzrKag
// parent-component.ts
@Component({
selector: 'parent-component',
template: `
<h1>Parent</h1>
<child-a-component [showNestedChild]="showNestedChildA"></child-a-component>
<child-b-component (toggleNested)="toggleShowNestedChildA($event)"></child-b-component>
`
})
class ParentComponent {
showNestedChildA: boolean = false;
public toggleShowNestedChildA(event) {
this.showNestedChildA = !this.showNestedChildA;
}
}
// child-a-component.ts
@Component({
selector: 'child-a-component',
template: `
<h2>Child A</h2>
<nested-child-a-component *ngIf="showNestedChild"></nested-child-a-component>
`
})
class ChildAComponent {
@Input() showNestedChild: boolean = false;
}
// nested-child-a-component.ts
@Component({
selector: 'nested-child-a-component',
template: `
<h3>Nested Child A</h3>
`
})
class NestedChildAComponent { }
// child-b-component.ts
@Component({
selector: 'child-b-component',
template: `
<h2>Child B</h2>
<button (click)="showNested()">Toggle Nested Child A</button>
`
})
class ChildBComponent {
@Output() toggleNested = new EventEmitter();
public showNested() {
this.toggleNested.emit(null)
}
}