search
HomeWeb Front-endJS TutorialA brief analysis of component templates in angular

This article will take you through the component templates in angular and briefly introduce the relevant knowledge points: data binding, property binding, event binding, two-way data binding, content projection, etc. ,I hope to be helpful!

A brief analysis of component templates in angular

Angular is a client## built using HTML, CSS, TypeScript #A framework for building single-page applications. [Related tutorial recommendations: "angular tutorial"]

Angular is a

heavyweight framework that integrates a large number ofout-of-the-box function module.

Angular is designed for large-scale application development and provides a clean and loosely coupled code organization method, making the application tidy and easier to maintain.

angualr Documentation:

  • Angular: https://angular.io/

  • Angular Chinese: https:// angular.cn/

  • Angular CLI: https://cli.angular.io/

  • Angular CLI Chinese: https://angular.cn/ cli

Component template

1. Data binding

Data binding That is, the data in the component class is displayed in the component template. When the data in the component class changes, it will automatically be synchronized to the component template (data-driven DOM).

Use

interpolation expression for data binding in Angular, that is, {{ }}<!-- -->.

<h2 id="message">{{message}}</h2>
<h2 id="getInfo">{{getInfo()}}</h2>
<h2 id="a-nbsp-nbsp-b-nbsp-nbsp-相等-nbsp-不等">{{a == b ? &#39;相等&#39;: &#39;不等&#39;}}</h2>
<h2 id="Hello-nbsp-Angular">{{&#39;Hello Angular&#39;}}</h2>
<p [innerHTML]="htmlSnippet"></p> <!-- 对数据中的代码进行转义 -->

2. Attribute binding

2.1 Common attributes

Attribute binding is divided into In two cases,

binds DOM object attributes and binds HTML tag attributes.

  • Use

    [property name] to bind DOM object properties to elements.

    <img  [src]="imgUrl"/ alt="A brief analysis of component templates in angular" >

  • Use

    [attr.attribute name]Bind HTML tag attributes to elements

    <td [attr.colspan]="colSpan"></td>

In most cases Below, DOM object attributes and HTML tag attributes are corresponding, so the first case is used.

But some attributes

only exist in HTML tags and do not exist in the DOM object. In this case, you need to use the second case, such as the colspan attribute, in the DOM object Just not.

Or custom HTML attributes also need to use the second case.

2.2 class attribute

<button class="btn btn-primary" [class.active]="isActive">按钮</button>
<div [ngClass]="{&#39;active&#39;: true, &#39;error&#39;: true}"></div>

2.3 style attribute

<button [style.backgroundColor]="isActive ? &#39;blue&#39;: &#39;red&#39;">按钮</button>
<button [ngStyle]="{&#39;backgroundColor&#39;: &#39;red&#39;}">按钮</button>

3. Event binding

<button (click)="onSave($event)">按钮</button>
<!-- 当按下回车键抬起的时候执行函数 -->
<input type="text" (keyup.enter)="onKeyUp()"/>
export class AppComponent {
  title = "test"
  onSave(event: Event) {
    // this 指向组件类的实例对象
    this.title // "test"
  }
}

4. Get the native DOM object

4.1 Get## in the component template #

<input>

4.2 Get

Use

ViewChild

decorator to get an element in the component class<pre class="brush:php;toolbar:false">&lt;p&gt;home works!&lt;/p&gt;</pre><pre class='brush:php;toolbar:false;'>import { AfterViewInit, ElementRef, ViewChild } from &quot;@angular/core&quot; export class HomeComponent implements AfterViewInit { @ViewChild(&quot;paragraph&quot;) paragraph: ElementRef&lt;HTMLParagraphElement&gt; | undefined ngAfterViewInit() { console.log(this.paragraph?.nativeElement) } }</pre>Use

ViewChildren

Get a set of elements <pre class='brush:php;toolbar:false;'>&lt;ul&gt; &lt;li #items&gt;a&lt;/li&gt; &lt;li #items&gt;b&lt;/li&gt; &lt;li #items&gt;c&lt;/li&gt; &lt;/ul&gt;</pre><pre class='brush:php;toolbar:false;'>import { AfterViewInit, QueryList, ViewChildren } from &quot;@angular/core&quot; @Component({ selector: &quot;app-home&quot;, templateUrl: &quot;./home.component.html&quot;, styles: [] }) export class HomeComponent implements AfterViewInit { @ViewChildren(&quot;items&quot;) items: QueryList&lt;HTMLLIElement&gt; | undefined ngAfterViewInit() { console.log(this.items?.toArray()) } }</pre>

5. Two-way data bindingData is synchronized in both directions in the component class and component template.

Angular places the two-way data binding function in the

@angular/forms

module, so to implement two-way data binding you need to rely on this module. <pre class='brush:php;toolbar:false;'>import { FormsModule } from &quot;@angular/forms&quot; @NgModule({ imports: [FormsModule], }) export class AppModule {}</pre><pre class='brush:php;toolbar:false;'>&lt;input type=&quot;text&quot; [(ngModel)]=&quot;username&quot; /&gt; &lt;button (click)=&quot;change()&quot;&gt;在组件类中更改 username&lt;/button&gt; &lt;div&gt;username: {{ username }}&lt;/div&gt;</pre><pre class='brush:php;toolbar:false;'>export class AppComponent { username: string = &quot;&quot; change() { this.username = &quot;hello Angular&quot; } }</pre>

6. Content projection

<!-- app.component.html -->
<bootstrap-panel>
	<div class="heading test">
        Heading
  </div>
  <div class="body">
        Body
  </div>
</bootstrap-panel>
<!-- panel.component.html -->
<div class="panel panel-default">
  <div class="panel-heading">
    <ng-content select=".heading"></ng-content>
  </div>
  <div class="panel-body">
    <ng-content select=".body"></ng-content>
  </div>
</div>
If there is only one ng-content, the select attribute is not required.

ng-content will be replaced by

in the browser. If you don't want this extra div, you can use ng -container replaces this div.

ng-content is usually used in projection: when the parent component needs to project data to the child component, it must specify where to project the data to the child component. At this time, you can use the ng-content tag. Making a placeholder will not produce a real DOM element, but will only copy the projected content.
  • ng-container is a special container tag that does not generate real dom elements, so adding attributes to the ng-container tag is invalid.
  • <!-- app.component.html -->
    <bootstrap-panel>
    	<ng-container class="heading">
            Heading
        </ng-container>
        <ng-container class="body">
            Body
        </ng-container>
    </bootstrap-panel>

7. Data binding fault tolerance processing

// app.component.ts
export class AppComponent {
    task = {
        person: {
            name: &#39;张三&#39;
        }
    }
}
<!-- 方式一 -->
<span *ngIf="task.person">{{ task.person.name }}</span>
<!-- 方式二 -->
<span>{{ task.person?.name }}</span>

8. Global style

/* 第一种方式 在 styles.css 文件中 */
@import "~bootstrap/dist/css/bootstrap.css";
/* ~ 相对node_modules文件夹 */
<!-- 第二种方式 在 index.html 文件中  -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet" />
// 第三种方式 在 angular.json 文件中
"styles": [
  "./node_modules/bootstrap/dist/css/bootstrap.min.css",
  "src/styles.css"
]
For more programming related knowledge, please visit:

Programming Video

! !

The above is the detailed content of A brief analysis of component templates in angular. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool