将参数传递给 Angular 中的组件提供者

问题描述 投票:0回答:1

我有一个继承自另一个组件的组件 -

@Component({
  template: '',
  providers: [
    {
        provide: NG_VALUE_ACCESSOR,
        useExisting: forwardRef(() => TComp),        
        multi: true,
      },
  ]
})
export abstract class FormBase<TComp> implements ControlValueAccessor {
   ...
   ...
}

还有另一个组件 -

@Component({
   selector: 'app-button',
   templateUrl: './button.component.html',
   styleUrls: ['./button.component.scss'],
})
export class ButtomComponent extends FormBase<ButtomComponent> {
   ...
   ...
}

我希望能够将子组件的引用传递给父组件,因此父组件可以添加提供程序而不是子组件(可能如上所示), 我想扩展此行为并继承其他组件中的 FormBase 并避免在每个子组件中声明 NG_VALUE_ACCESSOR 提供程序,

我找不到正确的方法来做到这一点,我收到错误无法找到名称 - TComp, 将感谢您的帮助!

angular inheritance angular-reactive-forms
1个回答
0
投票

当你继承一个类时,它不会继承

@Component
装饰器内容,所以无论你怎么看,你都不会在类之外导入父内容,所以你必须单独声明它们。

您可以编写一个实用函数来减少代码量,如下所示

实用性

export const addProviders = (component: any) => {
  return {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => component),
    multi: true,
  };
};

子组件

import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import {
  FormsModule,
  ReactiveFormsModule,
} from '@angular/forms';
import { addProviders, ParentComponent } from '../parent/parent.component';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css'],
  standalone: true,
  providers: [addProviders(ChildComponent)],
  imports: [CommonModule, FormsModule, ReactiveFormsModule, ParentComponent],
})
export class ChildComponent extends ParentComponent {
  constructor() {
    super();
  }

  ngOnInit() {}
}

堆栈闪电战

© www.soinside.com 2019 - 2024. All rights reserved.