


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!

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

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.

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.

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 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.

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.

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.


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

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
