


Angular development problem record: Component cannot get the @Input input attribute
When I was implementing a feature at work recently, I encountered a small problem: AngularThe component cannot get the @Input input attribute. Although I am relatively familiar with these problems, it is necessary to find the problem. It’s a process, so I’ll summarize and record this issue.
[Related tutorial recommendation: "angular tutorial"]
I need to give a ComponentSet an input attribute@Input, okay, just code it, it’s not difficult.
The original code is like this:
@Component({ selector: 'my-menu', templateUrl: './main-menu.widget.html' }) export class MyMenuWidget { data: any[]; ... constructor(...) { this._changesSubscription = this._service.changes.pipe( map((data: any[]) => { ... return data; }) ).subscribe((data: any[]) => { this.data = data; }); } ... }
Add an input attribute:
@Component({ selector: 'my-menu', templateUrl: './main-menu.widget.html' }) export class MyMenuWidget { @Input() isMainMenu: boolean = false; data: any[]; ... constructor(...) { this._changesSubscription = this._service.changes.pipe( map((data: any[]) => { ... return data; }) ).subscribe((data: any[]) => { if (this.isMainMenu) { this.data = data.filter((d: any) => d.ID === 233); } else { this.data = data; } }); } ... }
Use it:
<my-menu [isMainMenu]="mainMenu"></my-menu>
Then I found that the input attribute isMainMenu in MyMenuWidget could never get the value. Is there something wrong with the spelling? I checked it and found that there was no problem at all, but I just couldn't get the value.
Take a closer look, ahhhh? ? ? , the subscription to an Observable is actually written in the constructor! ! ! Although writing this way can work normally in some scenarios and does not affect the function of the code, this way of writing is very irregular, causing problems just like the code in the example above. Therefore, during normal development, it is not recommended to write like this. So what is the correct way to write it?
Upload the code.
@Component({ selector: 'my-menu', templateUrl: './main-menu.widget.html' }) export class MyMenuWidget { @Input() isMainMenu: boolean = false; data: any[]; ... constructor(...) { ... } ngOnInit() { this._changesSubscription = this._service.changes.pipe( map((data: any[]) => { ... return data; }) ).subscribe((data: any[]) => { if (this.isMainMenu) { this.data = data.filter((d: any) => d.ID === 233); } else { this.data = data; } }); } ... }
Then the question is, why can the same code work normally when placed in ngOnInit? Some people will say that we should just put it in ngOnInit, but not in the constructor. So why not, needs to be figured out.
The question is, what is the difference between the Angular constructor and the ngOnInit function?
Difference 1
Language difference:
Let’s first look at their differences from a language perspective. ngOnInit is just a method on the component class. The structure is no different from other methods on the class, except that it has a specific name.
export class MyMenuWidget implements OnInit { ngOnInit() {} }
It’s okay to implement it or not. I can still write it like this, no problem at all. No explicit markup needs to implement this interface.
export class MyMenuWidget { ngOnInit() {} }
This is how to write ES6. How to write the above code in ES5?
The constructor is completely different from it. It will be called when creating a class instance.
export class MyMenuWidget { constructor(){} ngOnInit() {} }
Difference 2
Difference in component initialization process:
From the perspective of component initialization, the difference between the two is still very big. Angular's startup process has two main stages:
1. Construct the component tree; 2. Perform change detection;
When Angular constructs the component tree, it needs to create a component instance. First The constructor new will be called to create an instance, which is to call the constructor of the component class. All lifecycle hooks including ngOnInit are then called as part of the change detection phase.
When Angular starts change detection, the component tree has been built and the constructors of all components in the tree have been called. Additionally, each component's template node is added to the DOM at this point. Here you have access to all the data you need to initialize the component - DI provider, DOM, etc. The @Input communication mechanism is handled as part of the change detection phase, so @Input is not available in the constructor.
export class MyMenuWidget { constructor(private _elementRef: ElementRef){ ... } ngOnInit() {} }
Difference three
Functional difference:
For Angular constructor, it is mainly used for initialization and injection Dependencies. The usual approach is to put as little logic as possible into the constructor. Sometimes, even though you put a lot of logic, it does not affect the functionality.
For ngOnInit, Angular creates the DOM of the component, uses the constructor to inject all necessary dependencies, and calls ngOnInit after completing the initialization. This is a good place to execute component initialization logic.
Simply put , constructorThe constructor itself has nothing to do with Angular, ngOnInitThese hook functions are defined in Angular.
Summary
Now is it clear why @Input cannot get the value in the constructor? In the future, it will be clear which logic should be placed in the constructor and which should be placed in ngOnInit.
For more programming-related knowledge, please visit: Programming Teaching! !
The above is the detailed content of Angular development problem record: Component cannot get the @Input input attribute. 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

AI Hentai Generator
Generate AI Hentai for free.

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



This article will take you to continue learning angular and briefly understand the standalone component (Standalone Component) in Angular. I hope it will be helpful to you!

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

The Angular project is too large, how to split it reasonably? The following article will introduce to you how to reasonably split Angular projects. I hope it will be helpful to you!

How to customize the angular-datetime-picker format? The following article talks about how to customize the format. I hope it will be helpful to everyone!

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!

This article will take you through dependency injection, introduce the problems that dependency injection solves and its native writing method, and talk about Angular's dependency injection framework. I hope it will be helpful to you!

This article will give you an in-depth understanding of several special selectors in Angular: host, :host-context, ::ng-deep. I hope it will be helpful to you!

The NgModule module is an important point in Angular, because the basic building block of Angular is NgModule. This article will take you through the NgModule module in Angular. I hope it will be helpful to you!
