【问题标题】:Warnings while using [ngClass]使用 [ngClass] 时的警告
【发布时间】:2019-05-06 21:33:58
【问题描述】:

我有一个名为contact-list 的组件。该组件用于显示带有照片的联系人列表,如下所示:

  • 如图所示,默认情况下,我已突出显示第一个联系人(即列表项的 background -colortext-color 已更改)。
  • 我使用另一个名为 display 的组件在右侧显示此选定的联系人详细信息,如下所示:

这是contact-list组件代码:

HTML

 <mat-selection-list>
    <mat-list-option [ngClass]="{selected : contact.fullName == currentContact.fullName}"  *ngFor="let contact of contacts">
       <a mat-list-item (click)="onSelect(contact)"><img src="{{contact?.pictureUrl}}" > <span>{{ contact?.fullName }}</span> </a>
    </mat-list-option>
  </mat-selection-list>

TS

import {Component, EventEmitter, Input , Output, ViewChild } from 
   '@angular/core';
 import { IContact } from 'src/app/models/app.models';

@Component({
  selector: 'btn-contact-list',
  templateUrl: './contact-list.component.html',
  styleUrls: ['./contact-list.component.scss'],
   })

 export class ContactListComponent {

  @Input()
    public contacts:  IContact[] ;
  @Output() public select: EventEmitter<{}> = new EventEmitter(); 

  public currentContact: IContact;

  public ngOnInit(): void {
   if (this.contacts && this.contacts.length > 0) {
     this.currentContact = this.contacts[0];
     this.select.emit(this.currentContact);
   }
  }

  public onSelect(contact: IContact): void {
    this.currentContact = contact; 
    this.select.emit(contact); 
   }

 }

这个场景对我来说很好用:但是在控制台中我收到了这个警告:
[ngClass] 有什么问题?

【问题讨论】:

  • 尝试写联系人?.fullName
  • 我已经试过你的答案了,还是没有结果..:)

标签: angular typescript angular-material angular6


【解决方案1】:

在访问object 的属性之前,您应该对对象的undefined 进行额外检查。你可以修改你的代码如下 -

<mat-list-option 
     [ngClass]="{selected : contact && currentContact && contact.fullName == currentContact.fullName}"  
     *ngFor="let contact of contacts">

【讨论】:

  • 现在我无法默认突出显示第一个contact...:)
  • 默认没有设置currentContact
  • 如何设置currentContact为默认值?
  • 以前很好,实现api后我面临这个问题..:)
猜你喜欢
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2017-03-23
  • 2017-11-19
  • 2012-12-14
  • 2017-05-05
  • 2016-09-02
  • 2013-12-05
相关资源
最近更新 更多