从另一组件单击按钮时,如何刷新一个组件(导航栏)?

时间:2018-06-23 07:18:47

标签: javascript angular rest angular6

我想从另一个组件Angular 6中单击按钮后重新加载组件。

1 个答案:

答案 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。