angular 组件传值交互

组件1 

html

<button (click)="showView(entity)">数据预览</button>

ts

import { DataSharingService } from "../../components/test";

constructor(private dataService: DataSharingService){}

showView(data) {

    this.dataService.toggleButton(true);

}

test文件

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

import { BehaviorSubject } from 'rxjs';

@Injectable({

  providedIn: 'root'

})

export class DataSharingService {

  private showButtonSubject = new BehaviorSubject<boolean>(true);默认值true

  public showButton$ = this.showButtonSubject.asObservable();

  public toggleButton(value: boolean): void {

    this.showButtonSubject.next(value);

  }

}

组件2

ts

import { DataSharingService } from './test';

constructor(private dataService: DataSharingService){}

 showBtn:Boolean=true;

 this.dataService.showButton$.subscribe((value: boolean) => {

      this.showBtn = value;

    });

html

<section *ngIf="showBtn" >

   .......

    </section>

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Angular 中,组件之间传递数据可以通过输入属性(@Input)、输出属性(@Output)和服务(Service)来实现。 1. 输入属性(@Input) 在父组件中通过属性绑定的方式将数据传递给子组件,子组件通过 @Input 装饰器来接收数据。 父组件: ```html <app-child [message]="parentMessage"></app-child> ``` ```typescript export class ParentComponent { parentMessage = 'Message from parent'; } ``` 子组件: ```typescript import { Component, Input } from '@angular/core'; @Component({ selector: 'app-child', template: '<p>{{ message }}</p>' }) export class ChildComponent { @Input() message: string; } ``` 2. 输出属性(@Output) 在子组件中通过 EventEmitter 发出事件,父组件通过事件绑定的方式来接收数据。 子组件: ```typescript import { Component, EventEmitter, Output } from '@angular/core'; @Component({ selector: 'app-child', template: '<button (click)="sendMessage()">Send Message</button>' }) export class ChildComponent { @Output() messageEvent = new EventEmitter<string>(); sendMessage() { this.messageEvent.emit('Message from child'); } } ``` 父组件: ```html <app-child (messageEvent)="receiveMessage($event)"></app-child> ``` ```typescript export class ParentComponent { receiveMessage(message: string) { console.log(message); } } ``` 3. 服务(Service) 通过服务来实现组件之间的数据传递,可以在服务中定义一个公共的数据变量,然后在需要访问该数据的组件中注入该服务。 服务: ```typescript import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { message = 'Message from service'; } ``` 组件: ```typescript import { Component } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-child', template: '<p>{{ message }}</p>' }) export class ChildComponent { message: string; constructor(private dataService: DataService) { } ngOnInit() { this.message = this.dataService.message; } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值