Angular 2无法在ngOnInit()

时间:2016-11-03 10:57:53

标签: angular input

我需要在页面加载时更改输入的值。但是,我无法做到。这就是我在单独的html文件上创建输入的方式。

<form (submit)="some_function()">
<input (keypress)="some_function()" name="test" id="test-input" [(ngModel)]="test" [placeholder]="'NEED TO CHANGE INPUT TEXT' | translate"/>
<button type="submit">Submit </button>

然后在ts文件中我有这样的东西:

ngOnInit() {

    var element = document.getElementById("test-input");
    // If I console.log(element) I actually get it.

    element.textContent = "INPUT TEXT CHANGED??";
    // If I console.log(element.textContent) I get the input with changed text... but I can't see it otherwise

}

我在这里做错了什么?有什么帮助吗?

1 个答案:

答案 0 :(得分:4)

@Input变量在视图完全初始化之前不会传递给控制器​​(这是与ngOnInit不同的钩子)。首先,导入适当的钩子:

import { AfterViewInit } from "@angular/core";

然后声明您正在实现AfterViewInit钩子:

class YourController implements AfterViewInit

最后声明与hook有关的方法:

ngAfterViewInit() {
    var element = document.getElementById("test-input");
    // If I console.log(element) I actually get it.

    element.textContent = "INPUT TEXT CHANGED??";
    // If I console.log(element.textContent) I get the input with changed text... but I can't see it otherwise
}

应该做的伎俩(: