簡體   English   中英

如何獲取<p>標記動態值並使用 angular 2 將其傳遞到打字稿中

[英]How to fetch the <p> tag dynamic value and pass it into typescript using angular 2

我在 app.component.html 中有以下 html 標簽

  <p id="demo">dynamicValuegoeshere!!!</p>

上面的段落有一些由 javascript 插入的動態值。 但是目前我正在使用類型腳本並嘗試獲取上述值並將其作為函數的輸入參數傳遞。

我期待 app.component.ts 文件中的結果如下:

getValue(dynamicvalue){
console.log(dynamicvalue)  //It should print the current value of the <p id="demo"> which is dynamicvaluegoeshere!!!!
}

有人可以幫助我實現這一目標嗎? 如何讀取特定的<P>標記值並將其傳遞到 app.component.ts 文件中

更新:

我只是使用下面的代碼來獲取 app.component.ts 文件中的結果

getValue()
{
 alert(document.getElementById("#demo").innerHTML);
}

app.component.html :

<input type="submit" value="Submit" (click)="getValue()" id="submitBtn2" class="btn-primary btn-xs" >

輸出:

null

但是#demo 仍然有價值。

更新-最新:

app.component.ts :

  @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })

     export class AppComponent implements OnInit {
      @ViewChild('demo', { static: false }) private dynamicRef: ElementRef<HTMLElement>;

     getvalue() {
       return this.dynamicRef.nativeElement.innerHTML;    
    }

     alert(this.getvalue);

輸出:

this.dynamicRef.nativeElement.innerHTML

在此處輸入圖片說明

更新 - 最新:

使用alert(this.getValue())

回來 :

ERROR TypeError: Cannot read property 'nativeElement' of undefined

最終 - 工作更新

將 #demo 添加到<p>標簽中,解決了這個問題。

謝謝你們...!

將 ViewChild 裝飾器與模板引用和 ElementRef 包裝器一起使用。

import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  template: '<p #dynamic>Dynamic value</p>',
})
export class AppComponent implements AfterViewInit {
  @ViewChild('dynamic', { static: false }) private dynamicRef: ElementRef<HTMLElement>;

  get value() {
    return this.dynamicRef.nativeElement.innerHTML;    
  }

  ngAfterViewInit() {
    console.log('value of p: ', this.value) // value of p: Dynamic value
  }
}

如果要確保在組件需要時存在 ViewChild 中的引用,請使用 ngAfterViewInit 掛鈎而不是 ngOnInit。

這是一個工作示例(打開控制台): stackblitz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM