0

help to fix condition to display data. I get model of M through async service, so i use >model?.something< notation to avoid errors when model is still undefined. title is null or 'somestring'. Something wrong with expression. Whatever form i choose it always display one of cases. I have avoided this type expression early and can not translate correctly to typescript.

import { Component } from '@angular/core';
import { M } from './model';

@Component({
  selector: 'app-test',
  template: `
<p *ngIf="model1?.title !== null">
  Display text if title exist('common string')
</p>
<p *ngIf="model2?.title === null">
  Display text if title equal to null
</p>
  `,
  styleUrls: ['./test.component.css']
})

export class TestComponent {
  model1: M;
  model2: M;
  constructor() {
    this.model1 = {
      title: 'username'
    };
    this.model2 = {
      title: null
    };
  }
}

export class M {
    public title: string;

    public constructor(){}
}
6
  • there's nothing happening async here. Commented Nov 24, 2017 at 10:15
  • idk whats your problem here, can you explain more? Commented Nov 24, 2017 at 10:15
  • 1
    instantiate model class, model1: M = new M(); Commented Nov 24, 2017 at 10:21
  • @PrithiviRaj Why would this make a difference here? You don't even know if his model actually has a constructor. Commented Nov 24, 2017 at 10:27
  • @lexith You are right error should not come with the given sample but error will occur if he tries to give title like this.model1.title='username' so only he's getting error like model is undefined. May be the real code is missing here Commented Nov 24, 2017 at 10:55

1 Answer 1

1

Please Try:

<h1 *ngIf="model1.title!==null">
    OK
  </h1>

   <h1 *ngIf="model2.title!==null">
    OK
  </h1>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.