Home > Web Front-end > JS Tutorial > body text

Angular development problem record: Component cannot get the @Input input attribute

青灯夜游
Release: 2022-12-09 20:17:14
forward
2673 people have browsed it

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.

Angular development problem record: Component cannot get the @Input input attribute

[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;
        });
    }

  ...
}
Copy after login

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;
            }
        });
    }

  ...
}
Copy after login

Use it:

<my-menu [isMainMenu]="mainMenu"></my-menu>
Copy after login

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: &#39;my-menu&#39;,
	templateUrl: &#39;./main-menu.widget.html&#39;
})
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;
            }
        });
    }

  ...
}
Copy after login

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() {}
}
Copy after login

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() {}
}
Copy after login

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() {}
}
Copy after login

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() {}
}
Copy after login

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!

Related labels:
source:juejin.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!