我正在学习/工作于Angular项目,我已经做了很多事情并尝试以“正确的方式”去做,现在我想要做的是:
我想从子组件中获取变量(输出)到父组件,但我不想使用输出,也不想监听它,我想在父组件需要时获取它,类似于 child.getVariable()
。我看到一篇帖子说我应该使用 childview,但问题与我的不同,所以我想知道是否使用 childview 从子组件获取数据是一个好的实践方法?
我正在学习/工作于Angular项目,我已经做了很多事情并尝试以“正确的方式”去做,现在我想要做的是:
我想从子组件中获取变量(输出)到父组件,但我不想使用输出,也不想监听它,我想在父组件需要时获取它,类似于 child.getVariable()
。我看到一篇帖子说我应该使用 childview,但问题与我的不同,所以我想知道是否使用 childview 从子组件获取数据是一个好的实践方法?
将EventEmitter在子组件中注册为@Output:
@Output() onDatePicked: EventEmitter<any> = new EventEmitter<any>();
Emit value on click:
public pickDate(date: any): void {
this.onDatePicked.emit(date);
}
监听您父组件模板中的事件:
<div>
<calendar (onDatePicked)="doSomething($event)"></calendar>
</div>
在父组件中:
public doSomething(date: any):void {
console.log('Picked date: ', date);
}
您是否只需要从父组件模板中访问子组件变量?如果是这样,可以使用:
<child-component #childComponentRef></child-component>
然后你可以从父模板中访问#childComponentRef.someVariable。否则,我认为Angular团队推荐使用共享服务。它们更加灵活。请参见https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-and-children-communicate-via-a-service
import { CountryCodesComponent } from '../../components/country-codes/country-codes.component';
import { Component, ViewChild } from '@angular/core';
@Component({
selector: 'signup',
templateUrl: "signup.html"
})
export class SignupPage {
@ViewChild(CountryCodesComponent)
countryCodes: CountryCodesComponent;
nationalPhoneNumber = '';
constructor() {}
get phoneNumber(): string {
return '+' + this.countryCodes.countryCode + this.nationalPhoneNumber;
}
}