简体   繁体   English

Angular 2无法更改ngOnInit()的输入值

[英]Angular 2 can't change input value at ngOnInit()

I need to change the value of an input when the page loads. 页面加载时,我需要更改输入的值。 However, I am not being able to. 但是,我不能。 This is how I created the input on a separate html file. 这就是我在单独的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>

Then in a ts file I have something like this: 然后在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

}

What am I doing wrong here? 我在这里做错了什么? Any help? 有什么帮助吗?

@Input variables are not passed to a controller until the view is fully initialized (that's a different hook from the ngOnInit). 在视图完全初始化之前,@ Input变量不会传递给控制器​​(这与ngOnInit不同)。 First, import the proper hook: 首先,导入适当的钩子:

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

then declare that you are implementing the AfterViewInit hook: 然后声明您正在实现AfterViewInit挂钩:

class YourController implements AfterViewInit

and finally declare the method related to the 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
}

Should do the trick (: 应该做到这一点(:

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

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