Home Web Front-end JS Tutorial A brief analysis of component templates in angular

A brief analysis of component templates in angular

May 16, 2022 am 11:02 AM
angular angular.js

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

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"/>
    Copy after login

  • Use

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

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

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>
Copy after login

2.3 style attribute

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

3. Event binding

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

4. Get the native DOM object

4.1 Get## in the component template #

<input type="text" (keyup.enter)="onKeyUp(username.value)" #username/>
Copy after login

4.2 Get

Use

ViewChild

decorator to get an element in the component class<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">&lt;p #paragraph&gt;home works!&lt;/p&gt;</pre><div class="contentsignin">Copy after login</div></div><div class="code" style="position:relative; padding:0px; margin:0px;"><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><div class="contentsignin">Copy after login</div></div>Use

ViewChildren

Get a set of elements <div class="code" style="position:relative; padding:0px; margin:0px;"><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><div class="contentsignin">Copy after login</div></div><div class="code" style="position:relative; padding:0px; margin:0px;"><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><div class="contentsignin">Copy after login</div></div>

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. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>import { FormsModule } from &quot;@angular/forms&quot; @NgModule({ imports: [FormsModule], }) export class AppModule {}</pre><div class="contentsignin">Copy after login</div></div><div class="code" style="position:relative; padding:0px; margin:0px;"><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><div class="contentsignin">Copy after login</div></div><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>export class AppComponent { username: string = &quot;&quot; change() { this.username = &quot;hello Angular&quot; } }</pre><div class="contentsignin">Copy after login</div></div>

6. Content projection

<!-- app.component.html -->
<bootstrap-panel>
	<div class="heading test">
        Heading
  </div>
  <div class="body">
        Body
  </div>
</bootstrap-panel>
Copy after login
<!-- 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>
Copy after login
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>
    Copy after login

7. Data binding fault tolerance processing

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

8. Global style

/* 第一种方式 在 styles.css 文件中 */
@import "~bootstrap/dist/css/bootstrap.css";
/* ~ 相对node_modules文件夹 */
Copy after login
<!-- 第二种方式 在 index.html 文件中  -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet" />
Copy after login
// 第三种方式 在 angular.json 文件中
"styles": [
  "./node_modules/bootstrap/dist/css/bootstrap.min.css",
  "src/styles.css"
]
Copy after login
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 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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

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!

Angular learning talks about standalone components (Standalone Component) Angular learning talks about standalone components (Standalone Component) Dec 19, 2022 pm 07:24 PM

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!

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

Angular + NG-ZORRO quickly develop a backend system Angular + NG-ZORRO quickly develop a backend system Apr 21, 2022 am 10:45 AM

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

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!

See all articles