【问题标题】:Auto refer to the components in the template?自动引用模板中的组件?
【发布时间】:2019-05-07 05:33:58
【问题描述】:

我正在使用 Angular 6 开发一个 Web 应用程序。是否可以引用模板中使用的组件(在本例中为我的 custom-component),例如本例:

<custom-component #select
   name="name1"
   title="Select first option"
   [(ngModel)]="select.value"

>
</custom-component>

如您所见,[(ngModel)] 属性的值为 select.value。这个值是 CustomComponent 的一个属性(我总是需要连接到 ngModel)。为了引用它,我使用了#select,但是 我想知道是否有其他方式或关键字允许我在模板中每次使用自定义组件时使用value 属性而不使用#select 装饰器。

【问题讨论】:

    标签: html angular6 components angular-components


    【解决方案1】:

    您可以在自定义组件上使用 ngModelControlValueAccessor

    custom-componen 类中扩展ControlValueAccessor

    export class CustomComponent implements  , ControlValueAccessor { 
    
        onChange = (val: string) => { };
        onTouched = () => { }; 
    
        writeValue(val: string): void { 
           // value passed from parent throug ngModel will come under this funtion
        }
    
        registerOnChange(fn: (val: string) => void): void {
            this.onChange = fn;
        }
    
        registerOnTouched(fn: () => void): void {
            this.onTouched = fn;
        } 
    
        ngOnInit() {
        } 
    
        // If you want to emit value to parent use the onChange function
        myEmitFunction(){
            this.onChange("value u want to emit")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 2016-05-18
      • 2019-08-26
      • 2017-06-12
      • 2021-11-27
      • 1970-01-01
      • 2019-07-05
      相关资源
      最近更新 更多