Angular 同级组件未从子组件获取更新的参数值-角度
我有父级、子级和兄弟级组件。当我们更改子组件中的参数值时。应触发同级组件方法,并应获取更新的值 我的问题是,我能够从父组件到同级组件触发该方法,但无法在触发时获得更新的值。有些耽搁 我使用两种不同的方法来传递参数和触发器方法,这可能是个问题。请帮忙 当子组件的邮政编码发生更改,但在触发时未在同级组件处获取邮政编码值时,此方法将从父组件触发 getSiblingSettingFn(){ } 子组件Angular 同级组件未从子组件获取更新的参数值-角度,angular,typescript,angular10,Angular,Typescript,Angular10,我有父级、子级和兄弟级组件。当我们更改子组件中的参数值时。应触发同级组件方法,并应获取更新的值 我的问题是,我能够从父组件到同级组件触发该方法,但无法在触发时获得更新的值。有些耽搁 我使用两种不同的方法来传递参数和触发器方法,这可能是个问题。请帮忙 当子组件的邮政编码发生更改,但在触发时未在同级组件处获取邮政编码值时,此方法将从父组件触发 getSiblingSettingFn(){ } 子组件 @Component({ selector: 'child-cmp', templa
@Component({
selector: 'child-cmp',
template: '<p>child</p>'
})
class ChildCmp {
@Output() childGInParameters = new EventEmitter<{ city: string, state: string, zip: string }>();
city: any = "Palmdale";
state: any = "CA";
zip: any = "93551";
setGeneralInfo() { // on change event
this.childGInParameters.emit({ city: this.city, state: this.state, zip: this.zip });
}
}
import { SiblingComponent } from '../SiblingComponent';
@Component({
selector: 'parent-cmp',
template: '<child-cmp (childGInParameters)="getGeneralInfo($event)" > </child-cmp>
<br/>
<sib-cmp [zip]="zip" [state]="state" [city]="city" ></sib-cmp>'
})
class ParentCmp {
@ViewChild('SiblingComponent') sibchild: SiblingComponent;
getGeneralInfo(childGInParameters: any) {
this.city = childGInParameters.city;
this.state = childGInParameters.state;
this.zip = childGInParameters.zip;
this.sibchild.getSiblingSettingFn();
}
}
@Component({
selector: 'sib-cmp'
})
class SiblingComponent {
@Input() zip: any;
@Input() state: any;
@Input() city: any;
ngOnChanges(changes: SimpleChanges) {
const c: SimpleChange = changes.zip;
this.zip = c.currentValue;
}
getSiblingSettingFn() {
}
}
试试这个,应该有用
ngOnChanges(更改:SimpleChanges){
if(changes.zip.previousValue){
this.zip=changes.zip.currentValue;
}
}
使用服务与不同组件交互,而不是父子直接关系。所以,您可能需要在父组件级和子组件级之间工作的服务
- 从父级到子级共享数据:@Input
- 从子级到父级共享数据:@ViewChild
- 将数据从子级共享到父级:@Output&EventEmitter
- 在不同组件之间共享数据:服务
请参阅组件交互-我使用了相同的代码,但在获取邮政编码值方面存在一些差距。第一个方法是调用,然后获取邮政编码值。这两个组件都不能正确处理。从不同的组件调用其他组件的方法不是一个好的做法。您需要放置一个服务来在不同的组件之间通信。