2016-11-03 18 views
1

ページの読み込み時に入力の値を変更する必要があります。しかし、私はできない。これは、私が別々のHTMLファイルに入力を作成する方法です。ngOnInit()で角2は入力値を変更できません

<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

あなたは入力で 'ngModel'を使ったように' ngOnInit'の中の入力値を変更することができます:this.test = "新しい値" – ranakrunal9

答えて

2

@入力変数は、ビューが完全に初期化されるまで(ngOnInitとは異なる)、コントローラに渡されません。まず、適切なフックインポート:

class YourController implements AfterViewInit 

、最終的にフックに関連する方法で宣言します:

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 
} 

が何をすべきを

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

を、あなたはAfterViewInitフックを実装していることを宣言トリック(:

関連する問題