search
HomeWeb Front-endJS TutorialAngular development practice (4): interaction between components

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, it is divided into three types: Transmission from parent component to child component, Transmission from child component to parent component and Transmission through service an interaction method.

The parent component passes to the child component

The child component defines input attributes through the @Input decorator, and then the parent component passes these input attributes to the child when referencing the child component. The component passes data, and sub-components can intercept changes in input attribute values ​​through setter or ngOnChanges().

First define two components, namely sub-component DemoChildComponent and 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
}

Child components define input attributes paramOne and paramTwo through @Input() (the attribute value can be any data type)

Parent component:

@Component({
  selector: &#39;demo-parent&#39;,
  template: `
    <demo-child [paramOne]=&#39;paramOneVal&#39; [paramTwo]=&#39;paramTwoVal&#39;></demo-child>
  `
})
export class DemoParentComponent {
    paramOneVal: any = &#39;传递给paramOne的数据&#39;;
    paramTwoVal: any = &#39;传递给paramTwo的数据&#39;;
}

The parent component references the child component DemoChildComponent in its template through the selector demo-child, and through the two input properties of the child component paramOne and paramTwo pass data to the subcomponent, and finally the two lines of data passed to paramOne and data passed to paramTwo are displayed in the template of the subcomponent text.

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, so at this time we need to use Go to the setter of the input attribute to intercept changes in the input attribute value.

We will transform the sub-component DemoChildComponent as follows:

@Component({
  selector: &#39;demo-child&#39;,
  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 setter of the paramOne attribute will The intercepted value val is assigned to the internal private property paramOneVal to achieve the effect of the parent component passing data to the 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

Use setter to intercept changes in input attribute valuesThe method can only monitor changes in a single attribute value , this method is 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.

Added ngOnChanges in subcomponent DemoChildComponent:

@Component({
  selector: &#39;demo-child&#39;,
  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}`);
            }
        }
    }
}

Parameters received by the new ngOnChanges method changes is an object with the input attribute name as the key and the value as SimpleChange. The SimpleChange object contains attributes such as whether the current input attribute changes for the first time, the previous value, and the current value. 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 will be added to the injector's container, the example of the parent component can be found through dependency injection.

The child component obtains the parent component instanceCompared to the parent component obtains the child component instance (directly through template variables, @ViewChild or @ViewChildren obtaining) is a little more troublesome.

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 Get a parent component reference of a known type directly by injecting DemoParentComponent in the constructor. The code example is as follows:

    @Component({
      selector: &#39;demo-child&#39;,
      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 unknown parent component

    A component may be For child components of multiple components, sometimes it is impossible to directly know the type of the parent component. In Angular, you can find it through Class-Interface(Class-Interface), that is, let the parent component provide a Class—InterfaceIdentifies an alias with the same name to assist in search.

    First create the DemoParent abstract class, which only declares the paramOneVal and paramTwoVal properties without implementation (assignment). The sample code is as follows:

    export abstract class DemoParent {
        paramOneVal: any;
        paramTwoVal: any;
    }

    Then define an alias Provider in the providers metadata of the parent component DemoParentComponent, and use useExisting to inject an instance of the parent component DemoParentComponent. The code example is as follows:

    @Component({
      selector: &#39;demo-parent&#39;,
      template: `
        <demo-child [paramOne]=&#39;paramOneVal&#39; [paramTwo]=&#39;paramTwoVal&#39;></demo-child>
      `,
      providers: [{provider: DemoParent, useExisting: DemoParentComponent}]
    })
    export class DemoParentComponent implements DemoParent {
        paramOneVal: any = &#39;传递给paramOne的数据&#39;;
        paramTwoVal: any = &#39;传递给paramTwo的数据&#39;;
    }

    Then in In the child component, you can find the example of the parent component through the DemoParent identifier. The example code is as follows:

    @Component({
      selector: &#39;demo-child&#39;,
      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: &#39;demo-child&#39;,
  template: `
    <p>子组件DemoChildComponent</p>
  `
})
export class DemoChildComponent implements OnInit {
    readyInfo: string = &#39;子组件DemoChildComponent初始化完成!&#39;;
    @Output() ready: EventEmitter = new EventEmitter<any>(); // 输出属性
    
    ngOnInit() {
        this.ready.emit(this.readyInfo);
    }
}

父组件:

@Component({
  selector: &#39;demo-parent&#39;,
  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(&#39;demoChild&#39;) 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 = &#39;我是CallService的info&#39;;
}

父组件:

@Component({
  selector: &#39;demo-parent&#39;,
  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 = &#39;我是被父组件改变的CallService的info&#39;;
    }
}

子组件:

@Component({
  selector: &#39;demo-child&#39;,
  template: `
    <button (click)="changeInfo()">子组件改变info</button>
  `
})
export class DemoChildComponent {
    constructor(public callService: CallService) {
        console.log(callService.info); // 打印结果:我是CallService的info
    }
    
    changeInfo() {
        this.callService.info = &#39;我是被子组件改变的CallService的info&#39;;
    }
}

上面的代码中,我们定义了一个CallService服务,在其内定义了info属性,后面将分别在父子组件通过修改这个属性的值达到父子组件互相传递数据的目的。

然后通过DemoParentComponent的providers元数据数组提供CallService服务的实例,并通过构造函数分别注入到父子组件中。

此时,通过父组件改变info按钮子组件改变info按钮在父组件或子组件中改变CallService服务的info属性值,然后在页面可看到改变之后对应的info属性值。

相关推荐:

Angular开发实践(三):剖析Angular Component

Angular开发实践(二):HRM运行机制

The above is the detailed content of Angular development practice (4): interaction between components. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment