Home > database >  How to pass data from app.component.ts to its app.module.ts in Angular?
How to pass data from app.component.ts to its app.module.ts in Angular?

Time:07-26

Due to the requirements of project I need to send data value dataOne in app.component.ts to its app.module.ts so that I can store it in variable moduleValue. Please refer code below and suggest how can achieve this transfer of data within files.

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'formcheck';

  dataOne: any;

  getValues(val: any) {
    console.warn(val);
    this.dataOne = val;
  }
}

app.module.ts

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

let moduleValue: any;

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
  
}

CodePudding user response:

I'd suggest that you declare a variable or an observable in a service, however, since you mentioned that you need to do this within the same files you might want to export a variable from your component and import it into your module like so:

app.component.ts

export class AppComponent {
  title = 'formcheck';

  dataOne: any;

  getValues(val: any) {
    console.warn(val);
    this.dataOne = val;
    DATA = this.dataOne;
  }
}

export var DATA = '';

app.module.ts

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { DATA } from './app.component';

let moduleValue: any;

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
  
}

CodePudding user response:

Here is the solution using service, I used BehaviorSubject for dynamic updation of value.

https://stackblitz.com/edit/angular-9pitmh?file=src/app/app.component.ts,src/app/app.component.html,src/app/app.module.ts,src/app/data.service.ts,src/app/hello.component.ts

  • Related