Detailed explanation of Angular component interaction steps
This time I will bring you a detailed explanation of the Angular component interaction steps. What are the precautions for the detailed explanation of the Angular component interaction steps. The following is a practical case, let's take a look.
In Angular application development, components can be said to be everywhere. This article will introduce several common component communication scenarios, which are methods for interaction between two or more components.
According to the direction of data transmission, there are three interaction methods: parent component to child component, child component to parent component, and service delivery.
The parent component passes it to the child component
The child component defines the input attribute through the @Input decorator, and then the parent component references the child component Pass data to subcomponents through these input properties, and subcomponents can intercept changes in input property values through setters or ngOnChanges().
First define two components, namely the sub-component DemoChildComponent and the parent component DemoParentComponent.
Sub-component:
@Component({ selector: 'demo-child', template: ` <p>{{paramOne}}</p> <p>{{paramTwo}}</p> }) export class DemoChildComponent { @Input() paramOne: any; // 输入属性1 @Input() paramTwo: any; // 输入属性2 }
The sub-component defines the input attributes paramOne and paramTwo (the attribute value can be any data type)
Parent component:
@Component({ selector: 'demo-parent', template: ` <demo-child [paramOne]='paramOneVal' [paramTwo]='paramTwoVal'></demo-child> ` }) export class DemoParentComponent { paramOneVal: any = '传递给paramOne的数据'; paramTwoVal: any = '传递给paramTwo的数据'; }
The parent component refers to the child component DemoChildComponent through the selector demo-child in its template, and Data is passed to the subcomponent through its two input attributes, paramOne and paramTwo. Finally, the two lines of text, the data passed to paramOne and the data passed to paramTwo, are displayed in the template of the subcomponent.
Interception of changes in input attribute values through setters
In practical applications, we often need to perform corresponding operations when an input attribute value changes. Then at this time we need to use the setter of the input attribute to intercept changes in the input attribute value.
We transform the sub-component DemoChildComponent as follows:
@Component({ selector: 'demo-child', template: ` <p>{{paramOneVal}}</p> <p>{{paramTwo}}</p> ` }) export class DemoChildComponent { private paramOneVal: any; @Input() set paramOne (val: any) { // 输入属性1 this.paramOneVal = val; // dosomething }; get paramOne () { return this.paramOneVal; }; @Input() paramTwo: any; // 输入属性2 }
In the above code, we can see that the intercepted value val is assigned to the internal private property paramOneVal through the setter of the paramOne property. Achieve the effect of parent component passing data to child component. Of course, the most important thing is that you can do more other operations in the setter, making the program more flexible.
Use ngOnChanges() to intercept changes in input attribute values
The method of intercepting changes in input attribute values through setter can only monitor changes in a single attribute value , this method becomes insufficient if multiple, interactive input attributes need to be monitored. By using the ngOnChanges() method of the OnChanges Life Cycle hook interface (called when the value of the variables explicitly specified by the component through the @Input decorator changes), you can monitor multiple input attribute values at the same time. Variety.
Add ngOnChanges in the sub-component DemoChildComponent:
@Component({ selector: 'demo-child', template: ` <p>{{paramOneVal}}</p> <p>{{paramTwo}}</p> ` }) export class DemoChildComponent implements OnChanges { private paramOneVal: any; @Input() set paramOne (val: any) { // 输入属性1 this.paramOneVal = val; // dosomething }; get paramOne () { return this.paramOneVal; }; @Input() paramTwo: any; // 输入属性2 ngOnChanges(changes: {[propKey: string]: SimpleChange}) { for (let propName in changes) { // 遍历changes let changedProp = changes[propName]; // propName是输入属性的变量名称 let to = JSON.stringify(changedProp.currentValue); // 获取输入属性当前值 if (changedProp.isFirstChange()) { // 判断输入属性是否首次变化 console.log(`Initial value of ${propName} set to ${to}`); } else { let from = JSON.stringify(changedProp.previousValue); // 获取输入属性先前值 console.log(`${propName} changed from ${from} to ${to}`); } } } }
The parameter changes received by the new ngOnChanges method is an object with the input attribute name as the key and the value as SimpleChange. The SimpleChange object contains the current input attribute. Whether it is the first change, previous value, current value and other attributes. Therefore, in the ngOnChanges method, multiple input attribute values can be monitored and corresponding operations performed by traversing the changes object.
Get the parent component instance
The previous introduction is that the child component defines the input attribute through the @Input decorator, so that the parent component can pass data to the child through the input attribute components.
Of course, we can think of a more proactive method, which is to obtain the parent component instance, and then call a property or method of the parent component to obtain the required data. Considering that each component instance is added to the injector's container, examples of parent components can be found through Dependency Injection.
It is more troublesome for the child component to obtain the parent component instance than the parent component to obtain the child component instance (obtained directly through template variables, @ViewChild or @ViewChildren).
To get the instance of the parent component in the child component, there are two situations:
The type of the parent component is known
In this case, you can Obtain the parent component reference of a known type directly by injecting DemoParentComponent in the constructor . The code example is as follows:
@Component({ selector: 'demo-child', template: ` <p>{{paramOne}}</p> <p>{{paramTwo}}</p> ` }) export class DemoChildComponent { paramOne: any; paramTwo: any; constructor(public demoParent: DemoParentComponent) { // 通过父组件实例demoParent获取数据 this.paramOne = demoParent.paramOneVal; this.paramTwo = demoParent.paramTwoVal; } }
The type of the unknown parent component
一个组件可能是多个组件的子组件,有时候无法直接知道父组件的类型,在Angular中,可通过类—接口(Class-Interface)的方式来查找,即让父组件通过提供一个与类—接口标识同名的别名来协助查找。
首先创建DemoParent抽象类,它只声明了paramOneVal和paramTwoVal属性,没有实现(赋值),示例代码如下:
export abstract class DemoParent { paramOneVal: any; paramTwoVal: any; }
然后在父组件DemoParentComponent的providers元数据中定义一个别名 Provider,用 useExisting 来注入父组件DemoParentComponent的实例,代码示例如下:
@Component({ selector: 'demo-parent', template: ` <demo-child [paramOne]='paramOneVal' [paramTwo]='paramTwoVal'></demo-child> `, providers: [{provider: DemoParent, useExisting: DemoParentComponent}] }) export class DemoParentComponent implements DemoParent { paramOneVal: any = '传递给paramOne的数据'; paramTwoVal: any = '传递给paramTwo的数据'; }
然后在子组件中就可通过DemoParent这个标识找到父组件的示例了,示例代码如下:
@Component({ selector: 'demo-child', template: ` <p>{{paramOne}}</p> <p>{{paramTwo}}</p> ` }) export class DemoChildComponent { paramOne: any; paramTwo: any; constructor(public demoParent: DemoParent) { // 通过父组件实例demoParent获取数据 this.paramOne = demoParent.paramOneVal; this.paramTwo = demoParent.paramTwoVal; } }
子组件向父组件传递
依然先定义两个组件,分别为子组件DemoChildComponent和父组件DemoParentComponent.
子组件:
@Component({ selector: 'demo-child', template: ` <p>子组件DemoChildComponent</p> ` }) export class DemoChildComponent implements OnInit { readyInfo: string = '子组件DemoChildComponent初始化完成!'; @Output() ready: EventEmitter = new EventEmitter<any>(); // 输出属性 ngOnInit() { this.ready.emit(this.readyInfo); } }
父组件:
@Component({ selector: 'demo-parent', template: ` <demo-child (ready)="onReady($event)" #demoChild></demo-child> <p> <!-- 通过本地变量获取readyInfo属性,显示:子组件DemoChildComponent初始化完成! --> readyInfo: {{demoChild.readyInfo}} </p> <p> <!-- 通过组件类获取子组件示例,然后获取readyInfo属性,显示:子组件DemoChildComponent初始化完成! --> readyInfo: {{demoChildComponent.readyInfo}} </p> ` }) export class DemoParentComponent implements AfterViewInit { // @ViewChild('demoChild') demoChildComponent: DemoChildComponent; // 通过模板别名获取 @ViewChild(DemoChildComponent) demoChildComponent: DemoChildComponent; // 通过组件类型获取 ngAfterViewInit() { console.log(this.demoChildComponent.readyInfo); // 打印结果:子组件DemoChildComponent初始化完成! } onReady(evt: any) { console.log(evt); // 打印结果:子组件DemoChildComponent初始化完成! } }
父组件监听子组件的事件
子组件暴露一个 EventEmitter 属性,当事件发生时,子组件利用该属性 emits(向上弹射)事件。父组件绑定到这个事件属性,并在事件发生时作出回应。
在上面定义好的子组件和父组件,我们可以看到:
子组件通过@Output()定义输出属性ready,然后在ngOnInit中利用ready属性的 emits(向上弹射)事件。
父组件在其模板中通过选择器demo-child引用子组件DemoChildComponent,并绑定了一个事件处理器(onReady()),用来响应子组件的事件($event)并打印出数据(onReady($event)中的$event是固定写法,框架(Angular)把事件参数(用 $event 表示)传给事件处理方法)。
父组件与子组件通过本地变量(模板变量)互动
父组件不能使用数据绑定来读取子组件的属性或调用子组件的方法。但可以在父组件模板里,新建一个本地变量来代表子组件,然后利用这个变量来读取子组件的属性和调用子组件的方法。
在上面定义好的子组件和父组件,我们可以看到:
父组件在模板demo-child标签上定义了一个demoChild本地变量,然后在模板中获取子组件的属性:
<p> <!-- 获取子组件的属性readyInfo,显示:子组件DemoChildComponent初始化完成! --> readyInfo: {{demoChild.readyInfo}} </p>
父组件调用@ViewChild()
本地变量方法是个简单便利的方法。但是它也有局限性,因为父组件-子组件的连接必须全部在父组件的模板中进行。父组件本身的代码对子组件没有访问权。
如果父组件的类需要读取子组件的属性值或调用子组件的方法,就不能使用本地变量方法。
当父组件类需要这种访问时,可以把子组件作为 ViewChild,注入到父组件里面。
在上面定义好的子组件和父组件,我们可以看到:
父组件在组件类中通过@ViewChild()获取到子组件的实例,然后就可以在模板或者组件类中通过该实例获取子组件的属性:
<p> <!-- 通过组件类获取子组件示例,然后获取readyInfo属性,显示:子组件DemoChildComponent初始化完成! --> readyInfo: {{demoChildComponent.readyInfo}} </p>
ngAfterViewInit() { console.log(this.demoChildComponent.readyInfo); // 打印结果:子组件DemoChildComponent初始化完成! }
通过服务传递
Angular的服务可以在模块注入或者组件注入(均通过providers注入)。
在模块中注入的服务在整个Angular应用都可以访问(除惰性加载的模块)。
在组件中注入的服务就只能该组件和其子组件进行访问,这个组件子树之外的组件将无法访问该服务或者与它们通讯。
下面的示例就以在组件中注入的服务来进行父子组件之间的数据传递:
通讯的服务:
@Injectable() export class CallService { info: string = '我是CallService的info'; }
父组件:
@Component({ selector: 'demo-parent', template: ` <demo-child></demo-child> <button (click)="changeInfo()">父组件改变info</button> <p> <!-- 显示:我是CallService的info --> {{callService.info}} </p> `, providers: [CallService] }) export class DemoParentComponent { constructor(public callService: CallService) { console.log(callService.info); // 打印结果:我是CallService的info } changeInfo() { this.callService.info = '我是被父组件改变的CallService的info'; } }
子组件:
@Component({ selector: 'demo-child', template: ` <button (click)="changeInfo()">子组件改变info</button> ` }) export class DemoChildComponent { constructor(public callService: CallService) { console.log(callService.info); // 打印结果:我是CallService的info } changeInfo() { this.callService.info = '我是被子组件改变的CallService的info'; } }
上面的代码中,我们定义了一个CallService服务,在其内定义了info属性,后面将分别在父子组件通过修改这个属性的值达到父子组件互相传递数据的目的。
然后通过DemoParentComponent的providers元数据数组提供CallService服务的实例,并通过构造函数分别注入到父子组件中。
At this time, change the info attribute value of the CallService service in the parent component or child component through the parent component changing the info button or the child component changing the info button, and then you can see the corresponding info attribute value after the change on the page.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of the use of Node module module (with code)
jQuery Cookie implementation of switching skin effect ( Code attached)
The above is the detailed content of Detailed explanation of Angular component interaction steps. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The default map on the iPhone is Maps, Apple's proprietary geolocation provider. Although the map is getting better, it doesn't work well outside the United States. It has nothing to offer compared to Google Maps. In this article, we discuss the feasible steps to use Google Maps to become the default map on your iPhone. How to Make Google Maps the Default Map in iPhone Setting Google Maps as the default map app on your phone is easier than you think. Follow the steps below – Prerequisite steps – You must have Gmail installed on your phone. Step 1 – Open the AppStore. Step 2 – Search for “Gmail”. Step 3 – Click next to Gmail app

WeChat is one of the social media platforms in China that continuously launches new versions to provide a better user experience. Upgrading WeChat to the latest version is very important to keep in touch with family and colleagues, to stay in touch with friends, and to keep abreast of the latest developments. 1. Understand the features and improvements of the latest version. It is very important to understand the features and improvements of the latest version before upgrading WeChat. For performance improvements and bug fixes, you can learn about the various new features brought by the new version by checking the update notes on the WeChat official website or app store. 2. Check the current WeChat version We need to check the WeChat version currently installed on the mobile phone before upgrading WeChat. Click to open the WeChat application "Me" and then select the menu "About" where you can see the current WeChat version number. 3. Open the app

When logging into iTunesStore using AppleID, this error saying "This AppleID has not been used in iTunesStore" may be thrown on the screen. There are no error messages to worry about, you can fix them by following these solution sets. Fix 1 – Change Shipping Address The main reason why this prompt appears in iTunes Store is that you don’t have the correct address in your AppleID profile. Step 1 – First, open iPhone Settings on your iPhone. Step 2 – AppleID should be on top of all other settings. So, open it. Step 3 – Once there, open the “Payment & Shipping” option. Step 4 – Verify your access using Face ID. step

Having issues with the Shazam app on iPhone? Shazam helps you find songs by listening to them. However, if Shazam isn't working properly or doesn't recognize the song, you'll have to troubleshoot it manually. Repairing the Shazam app won't take long. So, without wasting any more time, follow the steps below to resolve issues with Shazam app. Fix 1 – Disable Bold Text Feature Bold text on iPhone may be the reason why Shazam is not working properly. Step 1 – You can only do this from your iPhone settings. So, open it. Step 2 – Next, open the “Display & Brightness” settings there. Step 3 – If you find that “Bold Text” is enabled

Windows 11, as the latest operating system launched by Microsoft, is deeply loved by users. In the process of using Windows 11, sometimes we need to obtain system administrator rights in order to perform some operations that require permissions. Next, we will introduce in detail the steps to obtain system administrator rights in Windows 11. The first step is to click "Start Menu". You can see the Windows icon in the lower left corner. Click the icon to open the "Start Menu". In the second step, find and click "

Screenshot feature not working on your iPhone? Taking a screenshot is very easy as you just need to hold down the Volume Up button and the Power button at the same time to grab your phone screen. However, there are other ways to capture frames on the device. Fix 1 – Using Assistive Touch Take a screenshot using the Assistive Touch feature. Step 1 – Go to your phone settings. Step 2 – Next, tap to open Accessibility settings. Step 3 – Open Touch settings. Step 4 – Next, open the Assistive Touch settings. Step 5 – Turn on Assistive Touch on your phone. Step 6 – Open “Customize Top Menu” to access it. Step 7 – Now you just need to link any of these functions to your screen capture. So click on the first

Is the clock app missing from your phone? The date and time will still appear on your iPhone's status bar. However, without the Clock app, you won’t be able to use world clock, stopwatch, alarm clock, and many other features. Therefore, fixing missing clock app should be at the top of your to-do list. These solutions can help you resolve this issue. Fix 1 – Place the Clock App If you mistakenly removed the Clock app from your home screen, you can put the Clock app back in its place. Step 1 – Unlock your iPhone and start swiping to the left until you reach the App Library page. Step 2 – Next, search for “clock” in the search box. Step 3 – When you see “Clock” below in the search results, press and hold it and

If you don't have control over the zoom level in Safari, getting things done can be tricky. So if Safari looks zoomed out, that might be a problem for you. Here are a few ways you can fix this minor zoom issue in Safari. 1. Cursor magnification: Select "Display" > "Cursor magnification" in the Safari menu bar. This will make the cursor more visible on the screen, making it easier to control. 2. Move the mouse: This may sound simple, but sometimes just moving the mouse to another location on the screen may automatically return it to normal size. 3. Use Keyboard Shortcuts Fix 1 – Reset Zoom Level You can control the zoom level directly from the Safari browser. Step 1 – When you are in Safari
