user1477457
user1477457

Reputation: 23

String interpolation in Angular 2 not displaying updated value

I'm trying to learn Angular 2, and I'm running into a weird issue while following this documentation: https://angular.io/docs/ts/latest/guide/user-input.html for binding button clicks to a method on my controller.

I started off with their click event binding example. I created a simple app with the angular cli with ng new test-app and modified it so that it contains a single button that when I click, just adds a message to the page.

I have two components, the app component and the message components shown here:

message.component.html:

<p>{{message}}</p>

message.component.ts:

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

@Component({
  selector: 'app-message',
  templateUrl: './message.component.html',
  styleUrls: ['./message.component.css']
})
export class MessageComponent implements OnInit {

  message: string;

  constructor() {
    this.message = 'some initial message';
  }

  ngOnInit() {
  }

}

app.component.html:

<button (click)="addMessage()">Click</button>
<app-message *ngFor="let message of messages"></app-message>

app.component.ts:

import { Component } from '@angular/core';
import { MessageComponent } from './message/message.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  messages = [];

  addMessage() {
    const newMessage = new MessageComponent();
    newMessage.message = 'Something else entirely';
    this.messages.push(newMessage);
  }
}

When I run this with ng serve, the button appears as expected, but when I click the button, only the message some initial message appears despite being given a different value by my app controller. While doing a search I found a different way to do the one-way databinding by replacing the string interpolation with: <p [innerText]="message"></p> but the result is the same.

I'm kinda at a loss here as to why it won't display the updated value of Something else entirely.

Upvotes: 1

Views: 1360

Answers (1)

Julia Passynkova
Julia Passynkova

Reputation: 17909

MessageComponent component should take message as @Input:

export class MessageComponent implements OnInit {

 @Input() message: string;
}

AppComponent should send this input to its child like

 <app-message *ngFor="let message of messages" 
  [message]="message.message"></app-message>

Upvotes: 1

Related Questions