Angular2,TypeScript,如何读取/绑定属性值到组件类(在ngOnInit中未定义)

Tom*_*ino 18 typescript angular2-directives angular2-template angular

有人可以请教我如何读取/绑定属性值到@component类,这似乎是在ngOnInit方法中未定义?

这是一个有趣的演示:http://plnkr.co/edit/4FoFNBFsOEvvOkyfn0lw?p = preview

我想读取"someattribute"属性的值

<my-app [someattribute]="'somevalue'">
Run Code Online (Sandbox Code Playgroud)

在App类(src/app.ts)ngOninit方法中.

谢谢!

Thi*_*ier 16

您可以注意到这些参数不能用于根组件.有关详细信息,请参阅此问题:

解决方法包括利用ElementRef该类.它需要注入您的主要组件:

constructor(elm: ElementRef) {
  this.someattribute = elm.nativeElement.getAttribute('someattribute'); 
}
Run Code Online (Sandbox Code Playgroud)

我们需要在HTML文件中以这种方式使用组件:

<my-app someattribute="somevalue"></my-app>
Run Code Online (Sandbox Code Playgroud)


Ger*_*az0 16

你应该使用@Input装饰.

这是一个例子:

import { Component, Input } from '@angular/core';

@Component({
    selector: 'user-menu',
    templateUrl: 'user-menu.component.html',
    styleUrls: ['user-menu.component.scss'],
})
export class UserMenuComponent {

    /**
     * userName Current username
     */
    @Input('userName') userName: string;

    constructor() {

    }
    sayMyName() {
        console.log('My name is', this.userName);
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用它

<user-menu userName="John Doe"></user-menu>
Run Code Online (Sandbox Code Playgroud)

  • 这个答案不能解决在根组件上创建自定义属性的问题。尽管此解决方案是用于父/子组件属性绑定的文件,但对于方案(根组件),接受的答案是正确的。 (2认同)

Gün*_*uer 5

更新

根组件中不支持输入作为您可以使用的解决方法

constructor(elementRef:ElementRef) {
  console.log(elementRef.nativeElement.getAttribute('someattribute');
}
Run Code Online (Sandbox Code Playgroud)

另见https://github.com/angular/angular/issues/1858

另见固定的Plunker

原来的

您需要使用

[property]="value" 
Run Code Online (Sandbox Code Playgroud)

或者

property="{{value}}"
Run Code Online (Sandbox Code Playgroud)

或者如果它是一个属性

[attr.property]="value" 
Run Code Online (Sandbox Code Playgroud)

或者

attr.property="{{value}}"
Run Code Online (Sandbox Code Playgroud)