1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Angular2 動的に Directive や Component を切り替える技

Last updated at Posted at 2016-03-18

例えば、エラーを内容を表示させるページ内でエラー内容に応じて配下のDirectiveを切り替えたい場合があるかもしれない。

下記の様なDirectiveを2つ作成したとする。

server_error_directive.ts
@Directive({
  selector: 'サーバエラー'
})
@Template({
  inline:
    '<h1>Server Error!"</h1>'
})
class ServerErrorDirective {
  constructor() {
  }
}
auth.error.directive.ts
@Directive({
  selector: '認証エラー'
})
@Template({
  inline:
    '<h1>Auth Error!"</h1>'
})
class AuthErrorDirective {
  constructor() {
  }
}

これらを実際に表示したいエラーの種類に応じて表示しわけたいわけである。

技とは書いてみたが何のこともない、ngSwitch を利用するだけである。
これぞ KISS ( Keep It Simple, Stupid!)

app.component.ts

@Component({
  selector: 'my-app',
  directives: [ServerErrorDirective, AuthErrorDirective],
  template:
    `<div class="error" [ngSwitch]="_err.errorType()">
    <serverError *ngSwitchWhen="'serverError'"></serverError>
    <notFound *ngSwitchWhen="'notFound'"></notFound>
    </div>
    `
})
class AppComponent {
  type: string = 'serverError';
  constructor() {
  }
}

たぶんこんな感じで動くはず

参考URL
http://www.codelord.net/2015/05/19/angularjs-dynamically-loading-directives/

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?