angular - 将输入和输出从 HTML 移至 Angular 中的 Typescript

标签 angular typescript angular8

如何将父组件的所有输入和输出移至 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/

相关文章:

angular - 在 angular2 中迁移到 RC4 后的问题

angular - 为什么 $app-direction : rtl not working?

javascript - 需要在 Javascript 或 Angular 搜索时显示 JSON 中的父级和子级

angular-reactive-forms - 类型 'AbstractControl' 缺少类型 'FormGroup' : controls, registerControl、addControl、removeControl 和其他 3 个中的以下属性

angular - 更新 Angular 7 时出错 -> Angular 8

angular - NgxCharts 根据数据变化调整大小

javascript - 如何在 Angular 2 中编写窗口关闭事件处理程序?

typescript - Jest mockImplementationOnce 不覆盖手动模拟

javascript - 根据下拉列表中的选定值显示表单字段 Angular TypeScript

angular - 错误 TS2554 : Expected 2 arguments, 但使用 @ViewChild 得到 1