网站搜索

在 Angular 中将输入和输出从 HTML 移动到 Typescript


我如何将父组件的所有输入和输出从 HTML 移动到 Typescript?

我有以下内容,在父组件中有一个包含大量参数的长列表,负责向子组件发送和接收数据。希望它们能用 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,而不必担心复制输入/输出。

如果使用服务,会不会导致强类型的组件,其中父组件和子组件过于紧密连接?如果可能,希望采用智能-哑组件的架构策略,不知道使用服务是否可行。

答案#1

你可以使用 @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;
}

请参阅此 Stackblitz 示例演示。

答案#2

@Input - 使用共享服务在子组件中接收数据。

@输出 - 使用 subjects 来监听子组件中的变化。