用户从“角度材质自动完成”中选择一个值后,我想将该值传递给子组件。
我可以使用api中提供的optionSelected输出事件发射器来获得选定的值。但是我不确定最好还是最简单的方法是将值传递给子组件。
我很确定可以将服务用作中介,但是我认为可以在子组件中声明Input属性。
代码如下:
programs.component.html
<form>
<mat-form-field>
<input type="text" placeholder="ProgramName" aria-label="ProgramName"
matInput [formControl]="programNamesControl" [matAutocomplete]="auto" size="14" >
<mat-autocomplete #auto="matAutocomplete" (optionSelected)='getSelectedProgram($event.option.value)' >
<mat-option *ngFor="let option of filteredOptions | async" [value]="option" width:100px>
{{option}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<app-program-names-detail programNameSelected="programNameSelected" *ngIf="loadProgramDetails"></app-program-names-detail>
</form>
program.component.ts
import { ProgramService } from './../program.service';
import { Component, OnInit, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
@Component({
selector: 'app-programs',
templateUrl: './programs.component.html',
styleUrls: ['./programs.component.css']
})
export class ProgramsComponent implements OnInit {
programNamesControl = new FormControl();
programNames: string[] = [];
filteredOptions: Observable<string[]>;
programNameSelected: string;
loadProgramDetails: boolean;
constructor(private programService: ProgramService) {
}
ngOnInit() {
this.programService.getProgramNames().subscribe(data => {
this.programNames = data;
});
this.filteredOptions = this.programNamesControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
);
}
_filter(value: string): string[] {
console.log('Inside filter..');
return this.programNames.filter(programName =>
programName.toLowerCase().includes(value.toLowerCase())
);
}
getSelectedProgram(programNameVal) {
this.loadProgramDetails = true;
this.programNameSelected = programNameVal;
console.log('Program Selected is: ' + this.programNameSelected);
}
}
program-names-detail.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-program-names-detail',
templateUrl: './program-names-detail.component.html',
styleUrls: ['./program-names-detail.component.css']
})
export class ProgramNamesDetailComponent implements OnInit {
@Input('programNameSelected') programNameSelected: string;
constructor() { }
ngOnInit() {
console.log('program Name Selected: ' + this.programNameSelected);
}
}
我没有更改program-names-detail.component.html。
控制台日志显示:
选择的程序名称:programNameSelected