突出显示页面加载时默认的第一个列表项值,以angular

时间:2018-12-06 04:36:20

标签: angular typescript angular6

我有2个组成部分:1)contact 2)display

contact组件用于显示联系人列表,如下图所示:

enter image description here

另一个组件“显示”,我将其放置在contact组件的右侧,如下所示:

enter image description here

现在列表中changing/clicking个联系人(即联系人组件中的联系人)上。我正在右侧组件(即display组件)上显示特定的联系人数据(即电子邮件,性别...),如第二幅图像所示。

现在的问题是:

  • 我要默认突出显示第一个联系人。
  • 第一个突出显示的联系人数据(即电子邮件,性别...)将显示在右侧(即在显示组件上),与第二个图像一样
  

联系人组件代码

HTML

<mat-selection-list>
   <mat-list-option [ngClass]="{selected :  currentContact && 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>

SCSS

.selected {
  background-color:blue;
 }
.selected span{
  color:red;
 }

TS

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

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

export class ContactComponent {

@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); 
 }

}
  

显示组件代码

HTML

 <div>
  <tr>
      <td>Email </td>
      <td>{{contact?.eMailAddresses}} </td>
  </tr>
  <tr>
      <td>Gender</td>
      <td>{{contact?.gender}} </td>
  </tr>
 </div>

TS

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

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

export class DisplayComponent {

 @Input()
  public contact: IContact;

}

Stackblitz DEMO

1 个答案:

答案 0 :(得分:2)

尝试添加ngOnChanges来跟踪尚未加载的ngInint contacts上的联系人。

代码:

import { Component, Input, Output, EventEmitter, SimpleChanges, OnInit, ViewChild } from '@angular/core';

 ngOnChanges(changes: SimpleChanges) { 
  if (this.contacts && this.contacts.length > 0) { 
     this.currentContact = this.contacts[0]; 
     this.select.emit(this.currentContact); 
    } 
 }