简体   繁体   中英

Angular 6 Passing data from parent to child Bootstrap Modal

being a newbie to the angular 6 I am having a issue in passing data from one component to another component.

Actually i am opening child component bootstrap modal from parent modal and want to pass string parameter to child modal component and also want to call function as soon as modal opens and functions returns a array which is shown in table only.

Parent Component HTML

<div class="parent-comp">
    <div id="ext-modal" class="modal fade" role="dialog">
          <!-- Modal content Starts-->
          <app-f-ext [Id]="Id"></app-f-ext>
          <!-- Modal content Ends-->
        </div>
</div>

Child component TS

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

@Component({
  selector: 'app-premium-extension',
  templateUrl: './premium-extension.component.html',
  styleUrls: ['./premium-extension.component.css']
})
export class ExtensionComponent implements OnInit {
  @Input() Id: string;

  constructor() {

  }

  ngOnInit() {
  }

  callThisFunctionOnOpeningModal(){
   console.log(Id)
  }

}

Child component HTML

<div class="modal-dialog modal-lg">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">&times;</button>
      <h4 class="modal-title">Ext {{Id}}</h4>
    </div>
    <div class="modal-body">

    </div>
  </div>
</div>

Parent Component TS

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'ap-detail',
  templateUrl: './p-details.component.html',
  styleUrls: ['./p-details.component.css']
})
export class PDetailsComponent implements OnInit {
  Id: string;

  constructor(){
    this.Id = "test";
  }
}

When i open the modal it shows in the modal header but how to on call function on modal loads and passing the Id in that function.

Please don't down mark the question as i am in really big issue with this. Thanks in advance for the help.

You have to use the right selector to call your child component. So replace:

<!-- Modal content Starts-->
    <app-f-ext [Id]="Id"></app-f-ext>
<!-- Modal content Ends-->

By:

<!-- Modal content Starts-->
    <app-premium-extension [Id]="Id"></app-premium-extension>
<!-- Modal content Ends-->

And make sure to declare and initialize the Id var in your parent.component.ts file

You can then have access to the Id property in the ngOnInit function:

ngOnInit() {
   console.log(Id);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM