How to access Child Component HTML Element values in Parent Component in angular2?

﹥>﹥吖頭↗ 提交于 2019-12-06 02:56:26

If your components have a true parent/child relationship (one is nested within the other) then you can use the @Input and @Output decorators on properties to communicate between the two components.

I have a blog post about this here: https://blogs.msmvps.com/deborahk/passing-data-to-and-raising-an-event-from-a-nested-component/

Here is an example of a child component with @Input and @Output decorators:

import { Component, OnChanges, Input, EventEmitter, Output } from '@angular/core';

@Component({
    selector: 'pm-star',
    templateUrl: './star.component.html',
    styleUrls: ['./star.component.css']
})
export class StarComponent implements OnChanges {
    @Input() rating: number;
    starWidth: number;
    @Output() ratingClicked: EventEmitter<string> =
            new EventEmitter<string>();

    ngOnChanges(): void {
        this.starWidth = this.rating * 86 / 5;
    }

    onClick(): void {
        this.ratingClicked.emit(`The rating ${this.rating} was clicked!`);
    }
}

You can find the complete example here: https://github.com/DeborahK/Angular-GettingStarted

In any other scenario, you can build a service to communicate between your components, like this:

@Injectable()
export class ChildDataService {
  title: string;
  name: string;
}

See this plunker for more information: https://plnkr.co/edit/iODMVQzYwXcf5qJRR1El?p=preview

Not that I'm advocating the use of @ViewChild here (it's a tightly-coupled solution), but if you want to do it without the use of @Output properties, it's possible:

@Component({
  selector: 'child-component',
  template: `<input (change)='title=$event.target.value'>
             <input (change)='name=$event.target.value'>`
})

export class ChildComponent {
  title = "";
  name = "";
}

@Component({
  selector: 'parent-component',
  template: `<child-component #child></child-component><button type="submit" (click)="SaveCustomerDetails()">Submit</button>`,
})
export class ParentComponent {

  @ViewChild('child') myChild: ChildComponent;

  SaveCustomerDetails(){

    console.log(this.myChild.title + "" + this.myChild.name);
  }
}
}

I've modified your plunker here: https://plnkr.co/edit/mCGcIW1AVX2e9gEBzeC0?p=preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!