如何将父组件的所有输入和输出移至 Typescript,而不是 HTML?
我在父组件中有以下一长串参数,从子组件发送和接收数据。 希望它们出现在 Typescript 中。这怎么能转移呢?
<app-address-type-dropdown class="addresstype" (addressTypeChange)="addressTypeChangeEvent($event)"
[addressTypeDefaultItem]="addressEntryConfig.addressTypeDefaultValue"
[selectedAddressType]="addressEntryConfig.selectedAddressType"
[valuesToExclude]="addressEntryConfig.addressTypeDropdownListExclusion">
</app-address-type-dropdown>
目标:
<app-address-type-dropdown> </app-address-type-dropdown>
<!-- With input and output parameters in the Typescript file -->
- 目的是让人们更容易地根据自己的喜好重新排列 html/css,而不必担心复制输入/输出。
如果使用服务,是否会留下强类型组件,而父组件和子组件之间的联系过于紧密?更喜欢 smart-dumb 架构策略,无论服务是否可行。
最佳答案
您可以通过@ViewChild
获取子组件的引用,并在父组件代码中设置输入属性并订阅事件:
@ViewChild(AddressTypeDropdownComponent, { static: false }) child: AddressTypeDropdownComponent;
ngAfterViewInit() {
// Subscribe to the child component event
this.child.addressTypeChange.subscribe(value => {
console.log(value);
});
}
someMethod() {
// Set the input values of the child component
this.child.addressTypeDefaultItem = someValue1;
this.child.selectedAddressType = someValue2;
}
参见this stackblitz进行演示。
关于angular - 将输入和输出从 HTML 移至 Angular 中的 Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59549982/