基本元件和 LifeCycle 掛鉤

什麼是元件?

  • 元件基本上是一個使用更簡單配置的指令,適用於基於元件的體系結構,這是 Angular 2 的全部內容。將元件視為視窗小部件:你可以在 Web 應用程式的多個不同位置重用的 HTML 程式碼片段。

零件

angular.module('myApp', [])
    .component('helloWorld', {
        template: '<span>Hello World!</span>'
    });

標記

<div ng-app="myApp"> 
  <hello-world> </hello-world>
</div>

現場演示

在元件中使用外部資料:

我們可以新增一個引數來將名稱傳遞給我們的元件,其使用方法如下:

angular.module("myApp", [])
  .component("helloWorld",{
    template: '<span>Hello {{$ctrl.name}}!</span>',
    bindings: { name: '@' }
  });

標記

<div ng-app="myApp"> 
  <hello-world name="'John'" > </hello-world>
</div>

現場演示

在元件中使用控制器

我們來看看如何新增一個控制器。

angular.module("myApp", [])
  .component("helloWorld",{
      template: "Hello {{$ctrl.name}}, I'm {{$ctrl.myName}}!",
      bindings: { name: '@' },
      controller: function(){
        this.myName = 'Alain';
      }
  });

標記

<div ng-app="myApp">  
  <hello-world name="John"> </hello-world>
</div>

CodePen 演示

在 Angular 呼叫 $onInit 函式之前,傳遞給元件的引數在控制器的作用域中可用。考慮這個例子:

angular.module("myApp", [])
  .component("helloWorld",{
      template: "Hello {{$ctrl.name}}, I'm {{$ctrl.myName}}!",
      bindings: { name: '@' },
      controller: function(){
        this.$onInit = function() {
          this.myName = "Mac" + this.name;
        }
      }
  });

在上面的模板中,這將呈現“Hello John,我是 MacJohn!”。

請注意,$ctrlcontrollerAs 的 Angular 預設值(如果未指定)。

現場演示

使用 require 作為物件

在某些情況下,你可能需要從元件內的父元件訪問資料。

這可以通過指定我們的元件需要父元件來實現,require 將為我們提供所需元件控制器的引用,然後可以在我們的控制器中使用,如下例所示:

請注意,只有$ onInit 掛鉤後才能保證所需的控制器就緒。

angular.module("myApp", [])
  .component("helloWorld",{
      template: "Hello {{$ctrl.name}}, I'm {{$ctrl.myName}}!",
      bindings: { name: '@' },
      require: {
        parent: '^parentComponent'
      },
      controller: function () {
        // here this.parent might not be initiated yet

        this.$onInit = function() {
           // after $onInit, use this.parent to access required controller
           this.parent.foo();
        }

      }
  });

但請記住,這會在孩子和父母之間產生緊密的聯絡。