【问题标题】:How to read the property of a application selector at the time of initialization?如何在初始化时读取应用程序选择器的属性?
【发布时间】:2017-09-11 03:08:27
【问题描述】:

这是我的起始页面,它在后端呈现(而不是 'propval' 会有一个包含 json-configuration 的变量):

<%- include('template/head'); %>
<application [userdata]='"propval"'>
    Loading...
</application>
<%- include('template/foot'); %>

这是我处理“应用程序”选择器的组件:

@Component({
    moduleId: module.id,
    selector: 'application',
    templateUrl: './app.component.html',
    providers:[
        ProgressBar
    ]
})
export class AppComponent implements OnInit {

    public userdata;

    constructor(public progressBar :ProgressBar, private router: Router) {
        console.log("constructor",this.userdata);
    }

    public async ngOnInit() {
        console.log("ngOnInit",this.userdata);
    }

}

结果,在控制台中我得到:

constructor undefined
ngOnInit undefined

如何读取userdata 属性?也许这不会在AppComponent 中完成,因为application 选择器不会在app.component.html 中呈现。 application 选择器在后端呈现。

【问题讨论】:

  • 您是否尝试为此属性添加输入? @Input() 用户数据;
  • @galvan 是的,它不起作用
  • @Vega 不,它也没有用。
  • 你不能像这样将属性提供给你的应用组件,应该在服务中提供一个配置类型的对象并注入到组件中

标签: angular typescript


【解决方案1】:

question Vega shared 指出引导和入口组件不能使用输入绑定。 (我没有找到源代码,但是通过推理入口组件不应该有父组件,它们不会使用输入绑定是有道理的。)

接受的答案使用ElementRef 获取数据属性,该方法也适用于您的情况。

import {ElementRef} from '@angular/core';

constructor(private _ref: ElementRef) {}

ngOnInit() {
    this.userdata = this._ref.nativeElement.getAttribute('userdata');
}

Sample plunker

可能对您或其他人有用的其他解决方案:配置 InjectionToken (doc) 或使用服务。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 2020-03-05
    • 2011-12-28
    • 1970-01-01
    相关资源
    最近更新 更多