Angular 2 为什么我不能对标有@Attribute 的属性使用插值?

Angular 2 Why can't I use interpolation on attributes marked with @Attribute?

我有一个这样写的组件:

@Component({
selector: 'ams-text',
templateUrl: './text.component.html',
styleUrls: ['./text.component.scss']
})
export class TextComponent extends ElementBase<string> {

  constructor(
    @Attribute("name") public name : string,
    @Attribute("label") public label : string,
    ) {}
}

但是,如果我尝试像这样使用它:

<ams-text name="someName_{{ someNumber }}" label="{{someLabel}}"></ams-text>

Angular2 抛出这个错误:

Template parse errors:  Can't bind to 'label' since it isn't a known property of 'ams-text'.
1. If 'ams-text' is an Angular component and it has 'label' input, then verify that it is part of this module.
2. If 'ams-text' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.

现在 3 件事:

通常我不需要绑定到名称或标签,因为它们在组件的生命周期内不会改变。我可能想使用插值从变量初始化它们,但是当它们在屏幕上时,该变量不会更改其值。这正是插值给我带来的好处。

我通常会用静态文本初始化这些值,并且很少对这些属性使用插值,但确实会发生。再次说明为什么插值比使用 @Input 更有意义,因为使用 @Inputs.

的静态文本很麻烦

终于在name属性中插值没问题了。如果我从 label 属性中删除插值,它不会抱怨 name 并且实际上按我预期的那样工作。

我尝试了几种变体:

<ams-text name="someName_{{someNumber}}" attr.label="{{someLabel}}"></ams-text>
<ams-text name="someName_{{someNumber}}" attr-label="{{someLabel}}"></ams-text>

没有成功。

那么为什么我不能在组件上声明为 @Attribute 的字段中使用插值?我可以修复它吗?

如果您使用自定义 html 标签,那么它会报告您的模块上的模板解析 errors.Add 架构以抑制组件的此消息。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule ,CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; 
@NgModule({
  declarations: [
    AppComponent

  ],
  imports: [
    BrowserModule,


  ],
  schemas:[CUSTOM_ELEMENTS_SCHEMA],
  bootstrap: [],
  providers:[],
  entryComponents: [

  ]
})
export class AppModule {

}

您也可以使用 NO_ERRORS_SCHEMA 来禁止所有属性验证。

@Attribute()表示在创建组件时注入该值。这是一次性操作,发生在更改检测获取更改以解析绑定之前 ({{...}})。

如果您想使用绑定,请改用 @Input()

constructor() {}

@Input("name") public name : string;
@Input("label") public label : string;

有了这些输入,错误消息也会消失,因为它们告诉您您正在绑定到不存在的属性,将上述代码添加到组件后,情况就不再如此了。