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

时间:2017-07-21 18:46:11

标签: angular angular2-template

我有一个像这样编写的组件:

@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属性中删除插值,它不会抱怨名称,并且实际上按照我的预期工作。

我尝试了几种变体:

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

没有成功。

那么为什么我不能在组件上声明为@Attribute的字段中使用插值?我能解决吗?

2 个答案:

答案 0 :(得分:3)

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

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

constructor() {}

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

使用这些输入时,错误消息也会消失,因为它们告诉您绑定到不存在的属性,当上面的代码添加到组件时就不再这样了。

答案 1 :(得分:0)

如果您使用自定义html标记,那么它将报告模板解析错误。在模块上添加模式以禁止组件的此消息。

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来取消所有属性验证。