Angular 2 Sibling Component Communication

前端 未结 12 1499
深忆病人
深忆病人 2020-11-22 06:31

I have a ListComponent. When an item is clicked in ListComponent, the details of that item should be shown in DetailComponent. Both are on the screen at the same time, so

12条回答
  •  天涯浪人
    2020-11-22 07:26

    I also like to do the communication between 2 siblings via a parent component via input and output. it handles OnPush change notification better than using a common service. Or just use NgRx Store.

    Example.

    @Component({
        selector: 'parent',
        template: `
    `, styleUrls: ['./parent.component.scss'] }) export class ParentComponent { // create empty observable NotesList$: Observable = of([]); SelectedNote$: Observable = of(); //passed from note-grid for selected note to edit. ReceiveSelectedNote(selectedNote: Note) { if (selectedNote !== null) { // change value direct subscribers or async pipe subscribers will get new value. this.SelectedNote$ = of(selectedNote); } } //used in subscribe next() to http call response. Left out all that code for brevity. This just shows how observable is populated. onNextData(n: Note[]): void { // Assign to Obeservable direct subscribers or async pipe subscribers will get new value. this.NotesList$ = of(n.NoteList); //json from server } } //child 1 sibling @Component({ selector: 'note-edit', templateUrl: './note-edit.component.html', // just a textarea for noteText and submit and cancel buttons. styleUrls: ['./note-edit.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class NoteEditComponent implements OnChanges { @Input() gridSelectedNote: Note; constructor() { } // used to capture @Input changes for new gridSelectedNote input ngOnChanges(changes: SimpleChanges) { if (changes.gridSelectedNote && changes.gridSelectedNote.currentValue !== null) { this.noteText = changes.gridSelectedNote.currentValue.noteText; this.noteCreateDtm = changes.gridSelectedNote.currentValue.noteCreateDtm; this.noteAuthorName = changes.gridSelectedNote.currentValue.noteAuthorName; } } } //child 2 sibling @Component({ selector: 'notes-grid', templateUrl: './notes-grid.component.html', //just an html table with notetext, author, date styleUrls: ['./notes-grid.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class NotesGridComponent { // the not currently selected fromt eh grid. CurrentSelectedNoteData: Note; // list for grid @Input() Notes: Note[]; // selected note of grid sent out to the parent to send to sibling. @Output() readonly selectedNote: EventEmitter = new EventEmitter(); constructor() { } // use when you need to send out the selected note to note-edit via parent using output-> input . EmitSelectedNote(){ this.selectedNote.emit(this.CurrentSelectedNoteData); } } // here just so you can see what it looks like. export interface Note { noteText: string; noteCreateDtm: string; noteAuthorName: string; }

提交回复
热议问题