Angular cli 父传子,子传父,服务Service, @input,@output,@ViewChild 装饰器的简单使用,看这一篇就够了

news/2024/9/28 7:27:48

直接code

1:Angular cli 创建组件component

ng g component components\rightng g c wave  简写需要定位到根路径下即可创建组件Could not find an NgModule. Use the skip-import option to skip importing in NgModule.
PS C:\myAngulrDemos\20240428demo\mydemo01\src> cd ..
PS C:\myAngulrDemos\20240428demo\mydemo01> ng g component components\mynews
CREATE src/app/components/mynews/mynews.component.html (21 bytes)
CREATE src/app/components/mynews/mynews.component.spec.ts (626 bytes)
CREATE src/app/components/mynews/mynews.component.ts (275 bytes)
CREATE src/app/components/mynews/mynews.component.css (0 bytes)
UPDATE src/app/app.module.ts (486 bytes)
PS C:\myAngulrDemos\20240428demo\mydemo01> 

2:Angular cli 创建服务 service

ng g service services\mydata
在Angular中,服务是一种可重用的、负责特定任务的独立功能单元,比如获取数据、分享数据或者处理业务逻辑等。下面是如何创建和使用服务的步骤,以Angular的最新实践为准:创建服务
1:使用 @Injectable 装饰器: 所有的服务都需要使用 @Injectable() 装饰器来标记,这允许Angular的依赖注入系统识别并使用这个服务,下面为ts code:import { Injectable } from '@angular/core';@Injectable({providedIn: 'root', // 这使得服务成为一个单例,并在根模块级别提供
   })export class MyService {constructor() { }// 服务方法示例
     getData(): any {// 实现数据获取逻辑
     }}2:提供服务: 在上面的例子中,我们使用了 providedIn: 'root',这意味着服务会在根模块级别被提供,并且在整个应用程序中作为单例存在。如果你希望更细粒度地控制服务的生命周期,可以在模块的 providers 数组中声明服务。使用服务Service
2.1:注入服务: 要在组件、指令或其他服务中使用服务,你需要将其注入到构造函数中 ,下面为ts import { Component } from '@angular/core';import { MyService } from './my.service';@Component({selector: 'app-my-component',template: `<p>{{data}}</p>`,})export class MyComponent {data: any;constructor(private myService: MyService) { }ngOnInit() {this.data = this.myService.getData();}}

3:==== 父传子 使用 Input 装饰器

父 app-root:html
<h1>app root组件</h1>
<hr>
<p>参数:ptocback, pfunctionback:函数带到子组件</p>
<app-myparent [ptoc]="ptocback" [pfunction]="pfunctionback"></app-myparent>  //子组件
<router-outlet></router-outlet>父:ts
import { Component } from '@angular/core';@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent  {title = 'mydemo01';ptocback= "你好峰哥:"+Date.now().toLocaleString();pfunctionback(){alert("hello fengge");}
}
子:app-myparent   HTML
<p>myparent works!</p>
<h2>来自父组件的参数:{{ptoc}}</h2>
<hr><app-mychild></app-mychild>
<button (click)="pfunctionClick()">点击获取父组件的函数</button>子:ts
import { Component, OnInit } from '@angular/core';import { Input } from '@angular/core'; // 使用 input 装饰器 加 字段参数来传值 ,引入
@Component({selector: 'app-myparent',templateUrl: './myparent.component.html',styleUrls: ['./myparent.component.css']
})export class MyparentComponent implements OnInit {@Input() ptoc: any;  //这里要定义为any才行,接受来自父组件的数据
  @Input() pfunction() { }constructor(private data01service: Dataservice01Service) { }ngOnInit(): void {}pfunctionClick() {this.pfunction();}}

4:=====子传父 使用 ViewChild装饰器

父 app-myparent:html
<p>myparent works!</p>
<hr>
<app-mychild  #childData></app-mychild>
<button (click)="childDatatoParentClick()">点击获取子传父的数据</button>父:ts
import { Component, OnInit } from '@angular/core';
import { ViewChild } from '@angular/core';@Component({selector: 'app-myparent',templateUrl: './myparent.component.html',styleUrls: ['./myparent.component.css']
})export class MyparentComponent implements OnInit {@ViewChild("childData") childata: any;getChildData: any="";constructor() { }ngOnInit(): void {}childDatatoParentClick(){this.getChildData = this.childata.cNamealert("c->p:" + this.getChildData);}
}
子 app-mychild:html
<p>mychild works!</p>子 app-mychild:tsimport { Component } from '@angular/core';
@Component({selector: 'app-mychild',templateUrl: './mychild.component.html',styleUrls: ['./mychild.component.css']
})
export class MychildComponent implements OnInit {cName:any;constructor() { }ngOnInit(): void {this.cName = "我是Child组件的数据参数";}}

5:===组件使用Service服务传值或者获取数据

1:生成组件的命令 : ng g service services\mydataService01服务service  ts code
import { Injectable } from '@angular/core';@Injectable({providedIn: 'root'
})
export class Dataservice01Service {constructor() { }getData(){return "this Data from service 01";}
}
组件上使用 html
<button (click)="getdata01serverClick()">点击获取服务上的数据</button>\组件ts
import { Component, OnInit } from '@angular/core';
import { Dataservice01Service } from 'src/app/services/dataservice01.service'; //引入服务service 
@Component({selector: 'app-myparent',templateUrl: './myparent.component.html',styleUrls: ['./myparent.component.css']
})export class MyparentComponent implements OnInit {constructor(private data01service: Dataservice01Service) { //注入service 服务
  }ngOnInit(): void {}getdata01serverClick() {let ds = this.data01service.getData();alert("来自服务的数据:" + ds);}}

6:子传父 使用 @Output装饰器

步骤 1: 在子组件中定义输出属性

1.1:创建事件发射器: 在子组件类中,使用@Output()装饰器定义一个事件发射器。通常,我们会使用EventEmitter作为其类型,它能够发射任何类型的数据,
1.2:在这个例子中,我们定义了一个名为messageEvent的输出属性,类型为EventEmitter<string>,意味着它可以发射字符串类型的数据

子ts code:
import { Component, Output, EventEmitter } from '@angular/core';@Component({selector: 'app-child',template: `<button (click)="sendMessage()">发送消息给父组件</button>`
})
export class ChildComponent {@Output() messageEvent = new EventEmitter<string>();sendMessage() {this.messageEvent.emit("Hello from Child!");}
}

步骤 2: 在父组件模板中绑定事件
2.1:使用事件绑定: 在父组件的HTML模板中,通过事件绑定语法(())将子组件的输出事件与父组件中的一个方法绑定起来。

<!-- 父组件模板 -->
<app-child (messageEvent)="receiveMessage($event)"></app-child>
<p>{{ receivedMessage }}</p>

步骤 3: 在父组件类中处理事件

3.1:定义处理方法: 在父组件的类中,定义一个方法来接收并处理从子组件传来的数据
import { Component } from '@angular/core';@Component({selector: 'app-parent',templateUrl: './parent.component.html'
})
export class ParentComponent {receivedMessage: string;receiveMessage(message: string) {this.receivedMessage = message;}
}

7 最后来一张测试截图

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ryyt.cn/news/45771.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

业务数据脱敏

业务数据脱敏 一、什么是数据脱敏 先来看看什么是数据脱敏?数据脱敏也叫数据的去隐私化,在我们给定脱敏规则和策略的情况下,对敏感数据比如 手机号、银行卡号 等信息,进行转换或者修改的一种技术手段,防止敏感数据直接在不可靠的环境下使用。 像政府、医疗行业、金融机构、…

面试官问:Kafka 会不会丢消息?怎么处理的?

作者:Java3y链接:https://www.zhihu.com/question/628325953/answer/3281764326来源:知乎著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。面试官:今天我想问下,你觉得Kafka会丢数据吗? 候选者:嗯,使用Kafka时,有可能会有以下场景会丢消息 候选…

kafka 如何保证不重复消费又不丢失数据?

作者:Java3y链接:https://www.zhihu.com/question/483747691/answer/2392949203来源:知乎著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。面试官:今天我想问下,你觉得Kafka会丢数据吗? 候选者:嗯,使用Kafka时,有可能会有以下场景会丢消息 候选…

Angular 兄弟组件之间的传值

Angular 兄弟组件之间的传值 在Angular中,兄弟组件之间直接传递数据并不直接支持,但可以通过以下几种方式实现通信:1 使用服务(Service):创建一个服务,用于存储和管理需要共享的数据。在这个服务中定义一个BehaviorSubject或ReplaySubject(来自rxjs库),这些是可观察的对…

远光全栈AIGC数字创新平台入选“大模型行业应用十大典范案例”

6月4日至7日,由数字产业创新研究中心主办的2024中国数字企业峰会举行,远光软件自主研发的《全栈AIGC数字创新平台 YG-JT GPT》凭借其卓越的 AIGC技术创新实力与创新推广应用,成功入选“大模型行业应用十大典范案例”榜单。 本届峰会以“AI+ 数据x 向未来”为主题,聚焦AI+融…

《UML基础、案例与应用》习题记录-第20章

部分习题,使用visio或plantuml,非正确答案,仅供参考,欢迎评论,谢绝转载。 第20章 交互 20.6.2习题 1.略 2.3. 4. 5. 欢迎大家评论交流,发现博文中存在的问题一定要留言哦

远光九天平台荣获2024广东软件风云榜行业应用解决方案TOP10

6月13日,远光九天智能一体化云平台(简称:远光九天平台)在2024年粤港澳软件产业高质量发展大会、第十二届粤港云计算大会暨第七届粤港澳ICT大会,被授予2024广东软件风云榜“行业应用解决方案TOP10”奖项。 作为远光软件自主研发的全栈国产化技术底座,远光九天平台是采用云…