What is the best way to pass a specific property from a parent component to a child component in Angular when a button is clicked?

Hey there, I'm looking for a way to pass a single property (groupId) from a parent component to a child component. In this case, my child component is using ngx-bootstrap modal. Is there a solution available for this scenario? Essentially, I need to include the groupId in the group post object, and this groupId is currently accessible in the parent component.


Parent Component

group.component.ts

bsModalRef: BsModalRef;
group: any = {};

constructor(
  private router: Router,
  private route: ActivatedRoute,   
  private alertify: AlertifyService,
  private groupService: GroupService,
  private modalService: BsModalService
) { }

ngOnInit() {
   const id = +this.route.snapshot.paramMap.get('id');

   if (id) {
    this.groupService.getGroup(id)
     .subscribe(group => this.group = group);
   }
}

openModalWithComponent() {
   const initialState = {
     title: 'Add new post'
   };
   this.bsModalRef = this.modalService.show(PostModalComponent, {initialState});
   this.bsModalRef.content.closeBtnName = 'Close';
}

group.component.html

<div class="container">
  <div class="row">
    <div class="col-md-3">
      <a class="btn btn-primary btn-block">
        <button class="btn btn-primary fa fa-plus" (click)="openModalWithComponent()">Add 
         Post</button>
      </a>
    </div>
    <div class="col-md-3">
      <a class="btn btn-success btn-block" data-toggle="modal" data-target="#addCategoryModal">
        <i class="fa fa-plus"></i> Add Category
      </a>
    </div>
    <div class="col-md-3">
      <a class="btn btn-warning btn-block" data-toggle="modal" data-target="#addUserModal">
        <i class="fa fa-plus"></i> Add User
      </a>
    </div>
  </div>
</div>


Child Component

In this case, the child component utilizes the ngx-bootstrap modal.

post-modal.component.ts

title: string;
closeBtnName: string;
post: any = {};
postCaterogies;

constructor(
    public bsModalRef: BsModalRef,
    private postService: PostService
) { }

ngOnInit() {
    this.postService.getPostCategories()
    .subscribe(pCategories => this.postCaterogies = pCategories);
}

submit() {
  this.postService.createPost(this.post)
  .subscribe(post => {
     console.log(post);
  })
  this.bsModalRef.hide();
}

Answer №1

group.component.ts

bsModalRef: BsModalRef;
  group: any = {};

  constructor(
  private router: Router,
  private route: ActivatedRoute,   
  private alertify: AlertifyService,
  private groupService: GroupService,
  private modalService: BsModalService
  ) { }

  ngOnInit() {
   const id = +this.route.snapshot.paramMap.get('id');

   if (id) {
    this.groupService.getGroup(id)
     .subscribe(group => this.group = group);
   }
 }

  openModalWithComponent() {
const id = +this.route.snapshot.paramMap.get('id');
   const initialState = {
    title: 'Create New Post',
groupId: id
  };
   this.bsModalRef = this.modalService.show(PostModalComponent, {initialState});
   this.bsModalRef.content.closeBtnName = 'Close';
  }

post-modal.component.ts

  title: string;
  groupId: number;
  closeBtnName: string;
  post: any = {};
  postCategories;

  constructor(
   public bsModalRef: BsModalRef,
   private postService: PostService) { }

   ngOnInit() {
     this.postService.getPostCategories()
       .subscribe(pCategories => this.postCategories = pCategories);
  }

  submit() {
   this.postService.createPost(this.post)
    .subscribe(post => {
     console.log(post);
   })
  this.bsModalRef.hide();
  }

Answer №2

group.component.ts

openModalWithComponent() {
const id = +this.route.snapshot.paramMap.get('id');
   const initialState = {
    title: 'Add new post',
groupId: id
  };
   this.bsModalRef = this.modalService.show(PostModalComponent, {initialState});
   this.bsModalRef.content.closeBtnName = 'Close';
this.bsModalRef.content.onClose = (myData) => {
      // Perform actions with myData and then hide the modal
      this.bsModalRef.hide();
};
  }

post-modal.component.ts

onClose: any;
submit() {
   this.postService.createPost(this.post)
    .subscribe(post => {
     this.onClose({ value: post})
   })
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Angular UI Bootstrap accordion heading behavior when used in conjunction with a checkbox is causing

I have implemented a checkbox in the header of an accordion control using Bootstrap. However, I am facing an issue where the model only updates the first time the checkbox is clicked. Below is the HTML code for the accordion: <accordion ng-repeat="tim ...

What is preventing me from adding members to an imported declaration?

Currently, I am attempting to include a constructor in an imported declaration. As per the information provided in the documentation, this should be feasible. (Refer to Chapter Adding using an interface) Below is the code snippet that I have used: import ...

Grails3 and Angular profile as the default deployment configuration

What is the most effective approach to deploy the Grails3 war with an Angular profile (specifically Angular2)? My project is in Grails 3.2.9 and runs smoothly in development mode. I'm looking for a streamlined gradle build command that can create a co ...

The Authentication Key (FCM Token) was not provided in the request. For further details, please consult the "Authentication" section in the FCM documentation

When sending Firebase notifications from my NativeScript app using the Angular HTTP post module, I sometimes encounter an error stating that the request is missing an Authentication Key (FCM Token). The FCM documentation provides more information on this. ...

Error animation on client-side validation not resetting correctly

Incorporated a form validation and error display system utilizing TransitionGroup for animations. The flag issueVisible manages the visibility of the error message, while determineField() aids in identifying the field related to the error. The issue arise ...

Setting up conditional select options in Angular

I need to create a select list with specific options based on the data in an object. For instance, if the data property is 0, I want to display an option as 0 with the ability to switch to 1, and vice versa. However, when rendered in HTML, no option value ...

The process of prioritizing specific elements at the top of an array when ordering

In my array, I want to prioritize specific items to always appear at the top. The API response looks like this: const itemInventorylocationTypes = [ { itemInventorylocationId: '00d3898b-c6f8-43eb-9470-70a11cecbbd7', itemInvent ...

Contrasting covariant and contravariant positions within Typescript

I'm currently diving into the examples provided in the Typescript advanced types handbook to broaden my understanding. According to the explanation: The next example showcases how having multiple potential values for the same type variable in co-var ...

The server's response is unpredictable, causing Json.Parse to fail intermittently

I have encountered a strange issue that is really frustrating. It all started when I noticed that my Json.Parse function failed intermittently. Here is the code snippet in question: const Info = JSON.parse(response); this.onInfoUpdate(Info.InfoConfig[0]); ...

Routing with the default outlet in Angular

My current challenge involves the user module and setting up a default router outlet. The goal is to display the UserHomeComponent when the path is /user, but for some reason it's not functioning as expected. Interestingly, if I specify a path instead ...

Tips for retrieving modified data from a smart table in Angular 4

Currently, I am working on an angular project where I am utilizing smart table. Here is a snippet of my .html file: <ng2-smart-table [settings]="settings" [source]="source" (editConfirm)="onSaveConfirm($event)" (deleteConfirm)="onDeleteConfirm($event ...

The issue of not displaying the Favicon in Next.js is a common problem

I am currently using Next.js version 13.4.7 with the App directory and I am facing an issue with displaying the favicon. Even though the favicon image is located in the public folder and in jpg format, it is not being displayed on the webpage. However, w ...

Function useAppDispatch is missing a return type

.eslintrc.js module.exports = { root: true, extends: [ '@react-native-community', 'standard-with-typescript', 'plugin:@typescript-eslint/recommended', 'plugin:jest/recommended', 'plugin:p ...

Angular and Firebase application displays changes in the browser in approximately 10 seconds

I've encountered a peculiar problem with Angular 4 refresh when utilizing firebase authentication. I managed to replicate the issue in a basic application that should indicate if a user successfully logged in using firebase auth (Google account) or n ...

Is NATS.io compatible with React Native?

Struggling with integrating nats.io into a React Native project using Typescript has presented many challenges. Is there a way to successfully incorporate it without having to modify node_modules of nats (such as changing the "fs" import to "react-native-f ...

Sorting an array of objects in TypeScript may result in a type error

My data includes various categories, ages, and countries... const data = [ { category: 'Fish', age: 10, country: 'United Kingdom' }, { category: 'Fish', age: 9, country: 'United Kingdom' }, { category: ...

What is the most effective method for displaying indicators for in-flight requests in rxjs without causing side effects?

What is the best way to display a loading indicator for an ongoing request using RXJS (along with Angular2+) without causing side effects in the pipe() function? I've brainstormed some options. Is there a recommended approach or a better alternative? ...

The 'change' event is not being triggered by fromEvent within a Directive, but it is working with the 'click' event

Recently diving into the world of Angular and RxJS has left me with a question. I am attempting to listen for a change event on all mat-radio-group elements within a document. Oddly enough, when I use @HostListener, I am able to capture the event and log i ...

Why isn't my component calling the service.ts file?

In my Angular project, I am working on a home component that contains a specific method. This method is defined in a service file called service.ts and imported into the homecomponent.ts file. The method is named filterClicked with a condition within the s ...

Is there a way to extract a specific item from a ListView by tapping on it in Nativescript?

Attempting to retrieve data from a tap event using angular2 + typescript: This is the html code for the component: <RadListView row="1" [items]="groceryList" [class.visible]="listLoaded" (tap)="seeItem($event)" swipeActions="true" (itemSwipeProgr ...