简体   繁体   English

Angular - 如何从 typescript 访问模板变量/引用?

[英]Angular - How can I access Template variable/reference from typescript?

In my Angular project I am trying to access the value present in <td [innerHTML]='rupee.replaceHTML' #term></td> and assign it to vaiable newdata.在我的 Angular 项目中,我试图访问<td [innerHTML]='rupee.replaceHTML' #term></td>中存在的值并将其分配给可变的新数据newdata.

More on the functionality here, I have 2 buttons change and concourse .更多关于这里的功能,我有 2 个按钮changeconcourse The value present in below HTML will change when I press concourse button.当我按下concourse按钮时,HTML 下面的值会改变。 I was to save that changed value in variable newdata using localStorage so that I can access it later.我将使用localStorage将更改后的值保存在变量newdata中,以便以后可以访问它。

How can I access that html value and store it in new_data ?如何access that html value and store it in new_data

.html file .html文件

<mat-list-item>New Life</mat-list-item>
 <mat-list class="textFields">
   <table>
     <tr>
       <td [innerHTML]='rupee.replaceHTML' #term></td> ---> Access whatever value is here
      </tr>
     </table>                
 </mat-list>

//button
<button mat-raised-button type='button' (click)='concourse(kada, term)'>Confirm

            

component.ts组件.ts

export class Pinky { 
  @ViewChild('term') editElem!: ElementRef<HTMLTableDataCellElement>;
    

//button function       
concourse(rec: FillData, nada: HTMLTableDataCellElement) {
  const { a,b,c,d } = rec;
  let maan= nada.innerText;
  localStorage.setItem('FillData', JSON.stringify(rec));

   var new_data = JSON.parse(localStorage.getItem('FillData') || '{}') as FillData

-------------------//Can I access #term value here?-------------------------

    new_data.{{?}}= maan;                 ----------> Assign the  value here ?
    localStorage.setItem('FillData', JSON.stringify(new_data));
}

Interface界面

export interface DraneMan {
  maan:string;
}

You already have a @ViewChild('term') so you can just get it from this.editElem.innerHTML .您已经有一个@ViewChild('term') ,因此您可以从this.editElem.innerHTML中获取它。

What's more, you have a binding [innerHTML]='rupee.replaceHTML' , so, reading from the DOM something that is bound seems like the wrong data flow.更重要的是,您有一个绑定[innerHTML]='rupee.replaceHTML' ,因此,从 DOM 读取绑定的内容似乎是错误的数据流。 I would just use ruppee.replaceHTML as source of truth.我只会使用ruppee.replaceHTML作为事实来源。

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

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