我想从另一个组件Angular 6中单击按钮后重新加载组件。
答案 0 :(得分:0)
正如@MariyamMohammedJalil所说,您可以使用EventEmitter来触发第一个组件的更新。
请参阅以下示例:
first.component.ts
@Component({
selector: 'first-component',
template: '<div>{{label}}</label>
})
export class FirstComponent {
@Input() update: EventEmitter<string>;
label = 'First Component';
constructor() {}
ngOnInit() {
if (this.update) {
// Subscribe to the event emitter to receive an update event
this.update.subscribe((value: string) => {
this.refresh(value);
})
}
}
refresh(value: string) {
// Do your stuff here
this.label = value;
}
}
second.component.ts
@Component({
selector: 'second-component',
template: '<button (click)="updateFirstCmp()">Update First Component</button>'
})
export class SecondComponent {
@Input() update: EventEmitter<string>;
constructor(){}
updateFirstCmp() {
// Emit an event to update your first component
this.update.emit('Updated First Component');
}
}
例如,您应该在app.component.ts
中添加以下内容:
updateEventEmitter: EventEmitter<string>;
constructor() {
...
this.updateEventEmitter = new EventEmitter();
}
在您的app.component.html
中:
<first-component [update]="updateEventEmitter"></first-component>
<second-component [update]="updateEventEmitter"
解决问题的另一种方法是将first.component
输入为second.component
的输入参数,而无需使用EventEmitter
即可直接调用刷新功能。请参阅以下示例:
app.component.html
<first-component #firstComponent></first-component>
<second-component [firstCmp]="firstComponent"></second-component>
second.component.ts
@Component({
selector: 'second-component',
template: '<button (click)="updateFirstCmp()">Update First Component</button>'
})
export class SecondComponent {
@Input() firstCmp: FirstComponent;
constructor(){}
updateFirstCmp() {
// Update the first component directly
this.firstCmp.refresh('Updated First Component');
}
}
使用此示例,您不需要订阅更新事件,因为您没有使用EventEmitter。