Angular 2+:在模板中更改变量

时间:2017-11-08 01:56:03

标签: angular angular2-template

您如何从模板中更改现有的Typescript变量?

示例

<a class="header">{{myVar}}</a>

<mat-tab-group>
    <mat-tab label="{{ submission.FileName }}" *ngFor="let submission of submissions | async">

        <input myVar="submission.FileName" /> <-- SET VARIABLE HERE -->

    </mat-tab>
<mat-tab-group>

3 个答案:

答案 0 :(得分:0)

<input [myVar]='submission.FileName' />

在你的component.ts

import { Input } from '@angular/core';

@Input() myVar: any;

FONT:Angular Guide

答案 1 :(得分:0)

试试这个

<a class="header">{{myVar}}</a>
<mat-tab-group>
 <mat-tab label="{{ submission.FileName }}" *ngFor="let submission of submissions | async">
  <input [(ngModel)]="submission.FileName" (change)="myVar = submission.FileName"/> <-- SET VARIABLE HERE -->
 </mat-tab>
<mat-tab-group>

答案 2 :(得分:0)

找到解决方案

使用iframeload事件将当前UserName传递给设置myVar的函数。它工作但它也给了我一个更改错误,我需要导入并使用ChangeDetectorRef

<强>模板

<a class="header">{{myVar}}</a>

<mat-tab-group>
    <mat-tab label="{{ submission.FileName }}" *ngFor="let submission of submissions | async">
        <iframe (load)="message(submission.UserName)" style="width:0px; height:0px;"></iframe>
    </mat-tab>
</mat-tab-group>

<强>打字稿

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';

constructor(private afs: AngularFirestore, private cdRef:ChangeDetectorRef) { }

myVar;

message(userName) {
    this.myVar= userName;
    this.cdRef.detectChanges();
  }