search
HomeWeb Front-endJS TutorialDetailed explanation of template syntax in Angular

This article will give you a detailed introduction to the template syntax in Angular. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Detailed explanation of template syntax in Angular

Related tutorial recommendations: "angular tutorial"

Interpolation expression

  • test-interpolation.component.ts
@Component({
  selector: 'app-test-interpolation',
  templateUrl: './test-interpolation.component.html',
  styleUrls: ['./test-interpolation.component.css']
})
export class TestInterpolationComponent implements OnInit {

  title = '插值表达式';

  constructor() { }

  ngOnInit() {
  }

  getValue(): string {
    return '值';
  }
}
  • test-interpolation.component.html
<div class="panel panel-primary">
  <div class="panel-heading">基插值语法</div>
  <div class="panel-body">
    <h3>
      欢迎来到 {{title}}!
    </h3>
    <h3 id="nbsp-nbsp-nbsp-nbsp">2+2 = {{2 + 2}}</h3>
    <h3 id="调用方法-getValue">调用方法{{getValue()}}</h3>
  </div>
</div>

Template Variables

  • test-template-variables.component.ts
@Component({
  selector: &#39;app-test-template-variables&#39;,
  templateUrl: &#39;./test-template-variables.component.html&#39;,
  styleUrls: [&#39;./test-template-variables.component.css&#39;]
})
export class TestTempRefVarComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  public saveValue(value: string): void {
    console.log(value);
  }
}
  • test-template-variables.component.html
<div class="panel panel-primary">
  <div class="panel-heading">模板变量</div>
  <div class="panel-body">
    <input #templateInput>
    <p>{{templateInput.value}}</p>
    <button class="btn btn-success" (click)="saveValue(templateInput.value)">局部变量</button>
  </div>
</div>

Value binding, event binding, two-way binding

Value binding: []

  • test-value-bind.component.ts
@Component({
  selector: &#39;app-test-value-bind&#39;,
  templateUrl: &#39;./test-value-bind.component.html&#39;,
  styleUrls: [&#39;./test-value-bind.component.css&#39;]
})
export class TestValueBindComponent implements OnInit {

  public imgSrc = &#39;./assets/imgs/1.jpg&#39;;

  constructor() { }

  ngOnInit() {
  }
}
  • test-value-bind.component.html
<div class="panel panel-primary">
  <div class="panel-heading">单向值绑定</div>
  <div class="panel-body">
    <img  [src]="imgSrc" / alt="Detailed explanation of template syntax in Angular" >
  </div>
</div>

Event Binding: ()

  • test- event-bind-component.ts
@Component({
  selector: &#39;app-test-event-binding&#39;,
  templateUrl: &#39;./test-event-binding.component.html&#39;,
  styleUrls: [&#39;./test-event-binding.component.css&#39;]
})
export class TestEventBindingComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  public btnClick(event: any): void {
    console.log(event + &#39;测试事件绑定!&#39;);
  }
}
  • test-event-bind.component.html
<div>
    <div>事件绑定</div>
    <div>
        <button>点击按钮</button>
    </div>
</div>

Two-way binding: [()]

  • test-twoway-binding.component.ts
@Component({
  selector: &#39;app-test-twoway-binding&#39;,
  templateUrl: &#39;./test-twoway-binding.component.html&#39;,
  styleUrls: [&#39;./test-twoway-binding.component.css&#39;]
})
export class TestTwowayBindingComponent implements OnInit {

  public fontSizePx = 14;

  constructor() { }

  ngOnInit() {
  }

}
  • test-twoway-binding.component.html
<div class="panel panel-primary">
  <div class="panel-heading">双向绑定</div>
  <div class="panel-body">
    <app-font-resizer [(size)]="fontSizePx"></app-font-resizer>
    <div [style.font-size.px]="fontSizePx">Resizable Text</div>
  </div>
</div>
  • font-resizer.component.ts
@Component({
  selector: &#39;app-font-resizer&#39;,
  templateUrl: &#39;./font-resizer.component.html&#39;,
  styleUrls: [&#39;./font-resizer.component.css&#39;]
})
export class FontResizerComponent implements OnInit {

  @Input()
  size: number | string;

  @Output()
  sizeChange = new EventEmitter<number>();

  constructor() { }

  ngOnInit() {
  }

  decrement(): void {
    this.resize(-1);
  }

  increment(): void {
    this.resize(+1);
  }

  resize(delta: number) {
    this.size = Math.min(40, Math.max(8, +this.size + delta));
    this.sizeChange.emit(this.size);
  }
}
  • font-resizer.component.html
<div style="border: 2px solid #333">
  <p>这是子组件</p>
  <button (click)="decrement()" title="smaller">-</button>
  <button (click)="increment()" title="bigger">+</button>
  <label [style.font-size.px]="size">FontSize: {{size}}px</label>
</div>

Built-in structural directives

*ngIf

  • test-ng-if.component.ts
@Component({
  selector: &#39;app-test-ng-if&#39;,
  templateUrl: &#39;./test-ng-if.component.html&#39;,
  styleUrls: [&#39;./test-ng-if.component.css&#39;]
})
export class TestNgIfComponent implements OnInit {

  isShow = true;

  constructor() { }

  ngOnInit() {
  }
}
  • test- ng-if.component.html
<div class="panel panel-primary">
  <div class="panel-heading">*ngIf的用法</div>
  <div class="panel-body">
    <p *ngIf="isShow" style="background-color:#ff3300">显示内容</p>
  </div>
</div>

*ngFor

    ##test-ng-for.component.ts
  • @Component({
      selector: &#39;app-test-ng-for&#39;,
      templateUrl: &#39;./test-ng-for.component.html&#39;,
      styleUrls: [&#39;./test-ng-for.component.css&#39;]
    })
    export class TestNgForComponent implements OnInit {
    
      races = [
        {name: &#39;star&#39;},
        {name: &#39;kevin&#39;},
        {name: &#39;kent&#39;}
      ];
    
      constructor() { }
    
      ngOnInit() {
      }
    
    }
    test-ng-for.component.html
  • <div class="panel panel-primary">
      <div class="panel-heading">*ngFor用法</div>
      <div class="panel-body">
        <h3 id="名字列表">名字列表</h3>
        <ul>
          <li *ngFor="let name of names;let i=index;">
           {{i}}-{{name.name}}
          </li>
        </ul>
      </div>
    </div>

ngSwitch

    test-ng-switch.component.ts
  • @Component({
      selector: &#39;app-test-ng-switch&#39;,
      templateUrl: &#39;./test-ng-switch.component.html&#39;,
      styleUrls: [&#39;./test-ng-switch.component.css&#39;]
    })
    export class TestNgSwitchComponent implements OnInit {
    
      status = 1;
    
      constructor() { }
    
      ngOnInit() {
      }
    
    }
    test-ng-switch.component.html
  • <div class="panel panel-primary">
      <div class="panel-heading">ngSwitch用法</div>
      <div class="panel-body">
        <div [ngSwitch]="status">
          <p *ngSwitchCase="0">Good</p>
          <p *ngSwitchCase="1">Bad</p>
          <p *ngSwitchDefault>Exception</p>
        </div>
      </div>
    </div>

Built-in attribute directive

The relationship between HTML attributes and DOM attributes

    There is a one-to-one mapping relationship between a small number of HTML attributes and DOM attributes, such as id;
  • Some HTML attributes have no correspondence DOM attributes, such as colspan;
  • Some DOM attributes do not have corresponding HTML attributes, such as textContent;
  • Even if the names are the same, HTML attributes and DOM attributes are not the same thing;
  • The value of the HTML attribute specifies the initial value, and the value of the DOM attribute indicates the current value; the value of the HTML attribute cannot be changed, and the value of the DOM attribute can be changed.
  • Template binding works through DOM properties and events, not HTML attributes.

Note: Interpolation expression and attribute binding are the same thing, and interpolation expression belongs to DOM attribute binding.

NgClass

    test-ng-class.component.ts
  • @Component({
      selector: &#39;app-test-ng-class&#39;,
      templateUrl: &#39;./test-ng-class.component.html&#39;,
      styleUrls: [&#39;./test-ng-class.component.scss&#39;]
    })
    export class TestNgClassComponent implements OnInit {
      public currentClasses: {};
    
      public canSave = true;
      public isUnchanged = true;
      public isSpecial = true;
    
      constructor() { }
    
      ngOnInit() {
        this.currentClasses = {
          &#39;saveable&#39;: this.canSave,
          &#39;modified&#39;: this.isUnchanged,
          &#39;special&#39;: this.isSpecial
        };
      }
    }
    test-ng-class. component.html
  • <div class="panel panel-primary">
      <div class="panel-heading">NgClass用法</div>
      <div class="panel-body">
        <div [ngClass]="currentClasses">设置多个样式</div>
        <div [class.modified]=&#39;true&#39;></div>
      </div>
    </div>
    test-ng-class.component.less
  • .saveable {
        font-size: 18px;
    }
    
    .modified {
        font-weight: bold;
    }
    
    .special {
        background-color: #ff3300;
    }

NgStyle

    test-ng-style.component.ts
  • @Component({
      selector: &#39;app-test-ng-style&#39;,
      templateUrl: &#39;./test-ng-style.component.html&#39;,
      styleUrls: [&#39;./test-ng-style.component.css&#39;]
    })
    export class TestNgStyleComponent implements OnInit {
    
      currentStyles: { };
      canSave = false;
      isUnchanged = false;
      isSpecial = false;
    
      constructor() { }
    
      ngOnInit() {
        this.currentStyles = {
          &#39;font-style&#39;: this.canSave ? &#39;italic&#39; : &#39;normal&#39;,
          &#39;font-weight&#39;: !this.isUnchanged ? &#39;bold&#39; : &#39;normal&#39;,
          &#39;font-size&#39;: this.isSpecial ? &#39;36px&#39; : &#39;12px&#39;
        };
      }
    
    }
    test-ng-style.component.html
  • <div class="panel panel-primary">
      <div class="panel-heading">NgStyle用法</div>
      <div class="panel-body">
        <div [ngStyle]="currentStyles">
          用NgStyle批量修改内联样式!
        </div>
        <div [style.font-size]="isSpecial? &#39;36px&#39; : &#39;12px&#39;"></div>
      </div>
    </div>

NgModel

    test-ng-model.component.ts
  • @Component({
      selector: &#39;app-test-ng-model&#39;,
      templateUrl: &#39;./test-ng-model.component.html&#39;,
      styleUrls: [&#39;./test-ng-model.component.css&#39;]
    })
    export class TestNgModelComponent implements OnInit {
    
      name = &#39;kevin&#39;;
    
      constructor() { }
    
      ngOnInit() {
      }
    
    }
    test-ng-model.component.html
  • <div class="panel panel-primary">
        <div class="panel-heading">NgModel的用法</div>
        <div class="panel-body">
            <p class="text-danger">ngModel只能用在表单类的元素上面</p>
            <input type="text" name="name" [(ngModel)]="name">
        </div>
    </div>

Widget

Pipeline

Angular’s ​​built-in common pipes:

    uppercase and lowercase
uppercase Convert letters to uppercase {

{'aaa' | uppercase}} lowercase Convert letters to lowercase {
{'BBB' | lowercase}}

    Date
##{
{ birthday | date: 'yyyy-MM-dd HH:mm:ss'}}

number
{
{ pi | number: '2.2-2'}}

2.2-2: Indicates that 2-digit integer and 2-digit number are reserved decimal. 2-2: Indicates a minimum of 2 decimal places and a maximum of 2 decimal places.

Example
  • test-pipe.component.ts
@Component({
  selector: &#39;app-test-pipe&#39;,
  templateUrl: &#39;./test-pipe.component.html&#39;,
  styleUrls: [&#39;./test-pipe.component.css&#39;]
})
export class TestPipeComponent implements OnInit {

  currentTime: Date = new Date();
  
  str = &#39;aaa&#39;;

  money = 34.567;


  constructor() {
  }

  ngOnInit() {
    window.setInterval(
      () => { this.currentTime = new Date() }
      , 1000);
  }
}

test-pipe.component.html

<div class="panel panel-primary">
    <div class="panel-heading">管道的用法</div>
    <div class="panel-body">
      {{ currentTime | date:&#39;yyyy-MM-dd HH:mm:ss&#39; }}
    </div>
    <div class="panel-body">
      {{ str | uppercase }}
    </div>
    <div class="panel-body">
      {{ money | number: &#39;2.2-2&#39; }}
    </div>
</div>

Non-null assertion

test-not-null-assert.component.ts
  • @Component({
      selector: &#39;app-test-safe-nav&#39;,
      templateUrl: &#39;./test-not-null-assert.component.html&#39;,
      styleUrls: [&#39;./test-not-null-assert.component.css&#39;]
    })
    export class TestSafeNavComponent implements OnInit {
    
      public currentValue: any = null;
    
      constructor() { }
    
      ngOnInit() {
      }
    
    }
test-not-null-assert. component.html
  • <div class="panel panel-primary">
      <div class="panel-heading">安全取值</div>
      <div class="panel-body">
        名字:{{currentValue?.name}}
      </div>
    </div>
  • For more programming-related knowledge, please visit:
Programming Teaching

! !

The above is the detailed content of Detailed explanation of template syntax 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
The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

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.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

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 of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

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.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

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.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

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.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

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),