FiringBlanks
FiringBlanks

Reputation: 2084

Angular 2+: Changing variables within template

How would you change an existing Typescript variable from the template?

Example

<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>

Upvotes: 0

Views: 3182

Answers (3)

FiringBlanks
FiringBlanks

Reputation: 2084

Found the solution

Use an iframe and the load event to pass the current UserName to a function which sets myVar. It worked but it also gave me a change error, for which I need to import and use ChangeDetectorRef.

Template

<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>

Typescript

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

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

myVar;

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

Upvotes: 1

Jorawar Singh
Jorawar Singh

Reputation: 7621

Try this

<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>

Upvotes: 0

Albertino J&#250;nior
Albertino J&#250;nior

Reputation: 108

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

in your component.ts

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

@Input() myVar: any;

FONT: Angular Guide

Upvotes: 0

Related Questions