简体   繁体   English

角度2元素属性

[英]Angular 2 element attributes

When we call a component in Angular 2 like so <my-component></my-component> . 当我们在Angular 2中调用<my-component></my-component> Is it possible to pass in attrs here so that they can be used within the component class? 是否可以在此处传递属性,以便可以在组件类中使用它们?

example: 例:

<my-component data-is-live="true"></my-component>

// class
export class MyComponent {
    constructor() {
        console.log($attrs);
    }
} 

You can by simply specifying it as an input parameter: 您可以简单地将其指定为输入参数:

@Component({
    selector: 'my-component',
    template: `
    <p>Is it live: {{isLive}} </p>
  `
})
export class MyComponent {
    @Input('is-live') isLive: string;

    ngOnInit() {
        console.debug(this.isLive);
    }
}

See this plunkr: http://plnkr.co/edit/2E6XcNW6cTOblyhBOEwI?p=preview 看到这个plunkr: http ://plnkr.co/edit/2E6XcNW6cTOblyhBOEwI?p=preview

Note 注意

You can't use an attribute starting with data- , Angular2 seems to ignore those. 您不能使用以data-开头的属性,Angular2似乎会忽略这些属性。

是的,您可以在组件之间传递数据(例如,从父级到子级)。以下是具有不同方式的链接: 官方文档希望对您有所帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM