简体   繁体   English

如何在同一个 .ts 文件中的两个组件之间传输数据

[英]How to transfer data between two components in a same .ts file

I am working with Angular 7 and stuck on an approach, However, I gotta ask first, I have two classes on a same .ts file like so:我正在使用 Angular 7 并坚持使用一种方法,但是,我首先要问,我在同一个 .ts 文件中有两个类,如下所示:

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

@Component({
   selector: 'app-component',
   template: 'app.component.html',
   styleUrls: ['./app-component.css']
})
export class AppComponent{
   instruction:any;
   constructor() { }
}

@Component({
   selector: 'app-modal-component',
   template: 'app-modal.component.html'
})
export class AppModalComponent{
   constructor() { }
}

I want to transfer data from AppComponent to AppModalComponent .我想将数据从AppComponent传输到AppModalComponent Are they having Parent-Child relation or sibling relation?他们是亲子关系还是兄弟关系?

I had tried Input() & Output() methods.我试过Input()Output()方法。 But they do not seem to be working.但他们似乎没有工作。 The final option would be to use Setter and Getter through service(which I want to avoid for now.).最后一个选择是通过服务使用SetterGetter (我现在想避免使用。)。 Kindly assist in the matter.请协助处理此事。

Somehow I managed to transfer data through parameters and services to modal component, But having these types of components on a same page is not an appropriate way to implement Angular.不知何故,我设法通过parameters and services将数据传输到模态组件,但是将这些类型的组件放在同一页面上并不是实现 Angular 的合适方法。 So i break apart AppModalComponent as a saperate component and import it into the module of AppComponent所以我将AppModalComponent为一个单独的组件并将其导入到AppComponent的模块中

app.component.ts app.component.ts

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

@Component({
   selector: 'app-component',
   template: 'app.component.html',
   styleUrls: ['./app-component.css']
})
export class AppComponent{
   instruction:any;
   constructor() { }
}

app-modal.component.ts app-modal.component.ts

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

@Component({
   selector: 'app-modal-component',
   template: 'app-modal.component.html'
})
export class AppModalComponent{
   constructor() { }
}

app.module.ts app.module.ts

import { AppModalComponent } from '../path-to-import-app-modal.component';

@NgModule({
  declarations: [
    ...,
    ...,
    AppModalComponent
  ],
  imports: [],
  exports:[],
  providers: []
})

export class AppModule { }

This was the easiest and required way to get data through components, it only gets easy from here.这是通过组件获取数据的最简单和必需的方法,从这里开始变得容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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