Angular如何将ngModel数据从一个组件传递到另一个组件?

问题描述 投票:0回答:2

我试图将ngModel数据从一个组件传递到另一个组件,其中第二个组件可以使用该数据在其html中执行函数。

我正在使用@Input(),但我不知道如何通过超链接发送数据。

home.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { BasePageComponent } from 'src/app/partials/base-page/base-page.component';
import { ActivatedRoute } from '@angular/router';
import { SurveyService } from 'src/app/services/survey.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent extends BasePageComponent implements OnInit {

  @Input() surveyName: string;
  surveys: any[];

  constructor(
    route: ActivatedRoute,
    private surveyService: SurveyService) {
    super(route);
   }

  ngOnInit() {
    this.surveys = this.surveyService.getAll();
  }
}

home.component.html

<div
    class="col-4 col-sm-4 col-md-4 col-lg-4"
    *ngFor="let survey of surveys"
>
<a class="btn btn-outline-secondary" href="/about" role="button">Begin Survey</a>
</div>

about.component.html

<input type="text" [(ngModel)]="surveyName" oninput="loadSurvey(surveyName)">

现在,这没有做任何事情。我的预期结果是,当我点击Begin Survey时,about.component.html将加载我用loadSurvey(surveyName)方法点击的调查

angular mean-stack angular-services angular-ngmodel angular-components
2个回答
0
投票

您可以使用共享组件。

在一个组件中,您可以监听更改,并且可以在更改时将信息传输到另一个组件。

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject('default message');
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message);
  }

}

共享组件看起来很简单。

当你想发送信息时,你可以使用

this.data.changeMessage('your info');

在第二个组件中,您收到它。

this.data.currentMessage.subscribe(message => {
    console.log(message); //or whatever you want
}});

在这两个组件中,您可以导入您的服务,如:私有数据:构造函数中的DataService。

欲了解更多信息,您可以观看和阅读this


0
投票

在您的服务文件中

import { BehaviorSubject } from 'rxjs';


surveyName : any;
private pathSource = new BehaviorSubject(window.location.pathname);
currentPath = this.pathSource.asObservable();

changeValue(message: string) {
    this.pathSource.next(message)
}

在你的about组件文件中

loadSurvey(surveyName){
    this.service.changeValue(surveyName);
}

在home.component.ts文件中

ngOnInit() {
    this.service.changeValue.subscribe(message => {
        console.log(message); // you will get your survey name sended from home component
    })
}

希望对你有帮助

© www.soinside.com 2019 - 2024. All rights reserved.