简体   繁体   中英

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

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 {}
  
}

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 {}
  
}

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