代码之家  ›  专栏  ›  技术社区  ›  chubbsondubs

角度2为什么我不能对标记为@Attribute的属性使用插值?

  •  3
  • chubbsondubs  · 技术社区  · 8 年前

    我有一个这样写的组件:

    @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.
    

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

    @Input 因为将静态文本与 @Inputs .

    最后,它对名称属性中的插值没有问题。如果我从label属性中删除插值,它不会抱怨名称,实际上正如我所期望的那样工作。

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

    没有成功。

    那么为什么我不能在声明为 @Attribute 在组件上?我能修一下吗?

    2 回复  |  直到 8 年前
        1
  •  3
  •   0mpurdy    8 年前

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

    如果要使用绑定,请使用 @Input()

    constructor() {}
    
    @Input("name") public name : string;
    @Input("label") public label : string;
    

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

        2
  •  0
  •   yurzui    8 年前

    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 抑制所有属性验证。

    推荐文章