如何使用Angular创建TypeScript组件?

时间:2015-11-23 13:30:02

标签: angular typescript

我正在尝试使用TypeScript创建一个Angular组件。我正在尝试使用document.createElement创建我的组件来创建工具栏,但它没有生成。

这是我的组件代码:

import {Directive, Component, bootstrap} from 'angular2/angular2';
import {ToolbarGroup} from './toolbar';

@Component({
  selector: 'option-menu',
  templateUrl: 'templates/options.html'
})

class OptionMenu {
  ToolbarGroup = new ToolbarGroup;
  constructor() {
  }
  /**
   * @argument Node for return this count of child
   * @returns count of child in a node
   */
  public getChildCount(node) {
    var number = node.childNodes.length;
    return number;
  }

  public createCols(colNumber, rowName, className) {

    for (var i = 0; i < colNumber; i++) {
      var col = document.createElement("DIV");
      var rowID = rowName.getAttribute('id');
      rowID += 'col' + i;
      col.setAttribute('id', rowID);
      console.log(col.getAttribute('id'));
      col.setAttribute("class", className);



      var textnode = document.createElement("DIV");
      var pading = document.createElement("br");
      var toobar = document.createElement("toolbar");



      //col.appendChild(this.createCloseButton(col));
      col.appendChild(toobar);
      col.appendChild(pading);


      textnode.setAttribute('id', 'insideCol' + col.getAttribute('id'));
      textnode.setAttribute('class', 'insideColConttent');

      textnode.setAttribute("ondrop", "drop2(event,insideCol" + col.getAttribute('id') + ")");
      textnode.setAttribute("ondragover", "allowDrop(event)");

      col.appendChild(textnode);

      rowName.appendChild(col);
    }

    return rowName;
  }


  public createRows(colNumber, selectorName) {

    var row = document.createElement("DIV");
    row.setAttribute("class", "row");

    if (colNumber == 1) {
      var rowlID = 'rowL1Child' + this.getChildCount(selectorName);
      row.setAttribute("id", rowlID);

      row = this.createCols(1, row, 'col-md-12 coluna-editor');
    } else if (colNumber == 2) {
      var rowlID = 'rowL2Child' + this.getChildCount(selectorName);
      row.setAttribute("id", rowlID);

      row = this.createCols(2, row, 'col-md-6 coluna-editor');
    } else if (colNumber == 3) {
      var rowlID = 'rowL3Child' + this.getChildCount(selectorName);
      row.setAttribute("id", rowlID);

      row = this.createCols(3, row, 'col-md-4 coluna-editor');
    } else if (colNumber == 4) {
      var rowlID = 'rowL4Child' + this.getChildCount(selectorName);
      row.setAttribute("id", rowlID);

      row = this.createCols(4, row, 'col-md-3 coluna-editor');
    }

    return row;
  }


  createOneLineOneColumn() {
    var el = document.getElementById('content-into-page');
    el.appendChild(this.createRows(1, el));
  }
  createOneLineTowColumn() {
    var el = document.getElementById('content-into-page');
    el.appendChild(this.createRows(2, el));
  }
  createOneLineThreeColumn() {
    var el = document.getElementById('content-into-page');
    el.appendChild(this.createRows(3, el));
  }
  createOneLineFourColumn() {
    var el = document.getElementById('content-into-page');
    el.appendChild(this.createRows(4, el));
  }

  public createCloseButton(colID) {

    var btn = document.createElement("A");
    btn.setAttribute('href', 'javascript:void(0)');
    btn.setAttribute('class', 'btn btn-flat btn-default mdi-navigation-close');
    btn.setAttribute('onclick', 'cleanCol(' + colID.getAttribute('id') + ')');
    return btn;
  }
  public removeRow(rowId) {

    var btn = document.createElement("A");
    btn.setAttribute('href', 'javascript:void(0)');
    btn.setAttribute('class', 'btn btn-flat btn-default mdi-navigation-close');
    btn.setAttribute('onclick', 'removeRow(' + rowId.getAttribute('id') + ')');
    return btn;
  }

  saveContent() {
    var content = document.getElementById('content-into-page');
   var json = this.mapDOM(content, true);
    //console.log(json);

    //print();
JSON.stringify(json)
console.log(json); 
 }


  public mapDOM(element, json) {
    var treeObject = {};

    //Recursively loop through DOM elements and assign properties to object
    function treeHTML(element, object) {
        object["type"] = element.nodeName;
        var nodeList = element.childNodes;
        if (nodeList != null) {
            if (nodeList.length) {
                object["content"] = [];
                for (var i = 0; i < nodeList.length; i++) {
                    if (nodeList[i].nodeType == 3) {
                        object["content"].push(nodeList[i].nodeValue);
                    } else {
                        object["content"].push({});
                        treeHTML(nodeList[i], object["content"][object["content"].length -1]);
                    }
                }
            }
        }
        if (element.attributes != null) {
            if (element.attributes.length) {
                object["attributes"] = {};
                for (var i = 0; i < element.attributes.length; i++) {
                    object["attributes"][element.attributes[i].nodeName] = element.attributes[i].nodeValue;
                }
            }
        }
    }
    treeHTML(element, treeObject);

    return (json) ? JSON.stringify(treeObject) : treeObject;
}  

}

bootstrap(OptionMenu,[ToolbarGroup]);

我要创建的组件:

 import {Inject, Injectable, Directive, View, Component, bootstrap} from 'angular2/angular2';

    @Component({
      selector: 'toolbar',
      templateUrl: 'templates/toolbar.html'

    })
    export class ToolbarGroup {


    }
    bootstrap(ToolbarGroup);

2 个答案:

答案 0 :(得分:1)

我需要生成元素,然后动态解析如下:

<div class="ui grid contructPage">
    <div class="two wide column">
        <div class="ui vertical fluid tabular menu">
            <a href="javascript:void(0)"><h4><i class="sidebar icon"></i></h4></a>
            <h4 class="ui horizontal divider header">
                <i class="tag icon"></i>
                Colunas
                </h4>
            <a href="javascript:void(0)" (click)="createOneLineOneColumn()" class="ui primary button item">|</a>
            <a href="javascript:void(0)" (click)="createOneLineTowColumn()" class="ui primary button item">| |</a>
            <a href="javascript:void(0)" (click)="createOneLineThreeColumn()" class="ui primary button item">| | |</a>
            <!--<a href="javascript:void(0)" (click)="createOneLineFourColumn()" class="ui primary button item">| | | |</a>-->

            <h4 class="ui horizontal divider header">
                <i class="tag icon"></i>
                        Opções
            </h4>
            <a id="drag1" onclick="preview()" href="javascript:void(0)" class="ui primary button item">Preview<i class="unhide icon"></i></i></a>

            <a id="drag1" (click)="saveContent()" href="javascript:void(0)" class="ui primary button item">Save<i class="disk outline icon"></i></a>

            <a id="drag2" (click)="destroy()" href="javascript:void(0)" class="ui primary red button item">Clean<i class="trash outline icon"></i></a>


        </div>
    </div>

    <div class="thirteen wide stretched column">
        <div class="ui segment">
            <div class="ui equal width grid container " id="{{[DVEContainer.componentId]}}" *ng-for="#page of DVEContainer.components;#i=index">

                <div class="column insideColConttent title" id="{{[page.componentId]}}" *ng-for="#page of page.components;">
                    <div class="ui buttons">
                        <button href="javascript:void(0)" class="ui button" (click)="createVideo(page)"><i class="film icon"></i></button>
                        <button href="javascript:void(0)" class="ui button" (click)="createImage(page)"><i class="photo icon"></i></button>
                        <button href="javascript:void(0)" class="ui button" (click)="createText(page)" onclick="initEditor()"><i class="write icon"></i></button>
                        <button href="javascript:void(0)" class="ui button" (click)=" removeElements(page)"><i class="erase icon"></i></button>
                    </div>
                    <div *ng-for="#page of page.components;">
                        <div *ng-if="[page.getHtmSelector()] =='textarea'">
                            <text-component>

                            </text-component>

                        </div>
                        <div *ng-if="[page.getHtmSelector()] =='img'">
                            <input type="text" [(ng-model)]="page.href" laceholder="Img Source" /> 
                            <img class="ui image" src="{{[page.href]}}" />
                        </div>
                        <div *ng-if="[page.getHtmSelector()] =='video'">
                            <input type="text" [(ng-model)]="page.href" (keyup)="showVideo(page)" onkeyup="resizeIframe()" placeholder="Video Source"
                            />

                            <br>

                            <iframe  src="{{[page.href]}}">
                            </iframe>
                        </div>
                    </div>
                </div>

            </div>

        </div>
    </div>
</div>
<div class="preview ui grid previewPage" style="display: none;">
<div class="ui grid">
  <div class="sixteen wide column">
      <a id="drag1" onclick="preview()" href="javascript:void(0)" class="ui primary button item right floated">Preview<i class="unhide icon"></i></i></a>
  </div>  
</div>

    <div class="ui equal width grid container " id="{{[DVEContainer.componentId]}}" *ng-for="#page of DVEContainer.components;#i=index">

        <div class="column insideColConttent title" id="{{[page.componentId]}}" *ng-for="#page of page.components;">

            <div *ng-for="#page of page.components;">
                <div *ng-if="[page.getHtmSelector()] =='textarea'">
                    <p>
                        {{[page.value]}}
                    </p>
                </div>
                <div *ng-if="[page.getHtmSelector()] =='img'">
                    <img class="ui image" src="{{[page.href]}}" />
                </div>
                <div *ng-if="[page.getHtmSelector()] =='video'">
                    <iframe src="{{[page.href]}}">
                    </iframe>
                </div>
            </div>
        </div>

    </div>

</div>

主要课程:

import {Directive, Component, bootstrap, Inject, View, NgFor, NgIf, EventEmitter,
CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass, NgStyle} from 'angular2/angular2';
import {Http, Response, HTTP_PROVIDERS, Headers} from 'angular2/http';
import{TextComponentDirective} from './Directives/TextComponentDirective';

//import {NgGrid,NgGridItem} from './Directives/NgGrid';
//API
import {DVE} from './API/DVE';


@Component({
  selector: 'dve-page',
  templateUrl: 'templates/DvePage.html',
  inputs: ['DVEContainer: DVEContainer', 'page:page', 'col:col', 'imagem:imagem', 'video:video'],
  directives: [NgFor, NgIf, NgClass, NgStyle, CORE_DIRECTIVES, FORM_DIRECTIVES,TextComponentDirective],

})




class OptionMenu {
  bosta = new DVE.Core.Plugin.bostaBugada();



  DVEContainer: DVE.Core.Definitions.Container;
  DVEtoolBar: DVE.Core.Plugin.Toolbar;
  DVEPage: DVE.Core.Definitions.Container;

  RowFactory: DVE.Core.Plugin.ContainerFactory;


  constructor() {

    this.DVEContainer = new DVE.Core.Definitions.Container();
    this.DVEContainer.setHtmSelector('row');


    let colL1 = new DVE.Core.Definitions.Container();
    colL1.setHtmSelector('col');
    this.DVEContainer.AddComponent(colL1);

    let colL2 = new DVE.Core.Definitions.Container();
    colL2.setHtmSelector('col');
    this.DVEContainer.AddComponent(colL2);



  }



  createOneLineOneColumn(): void {

    let rowL1 = new DVE.Core.Definitions.Container();
    let colOf = new DVE.Core.Definitions.Container();

    rowL1.setHtmSelector(DVE.Core.Plugin.Constants.ROW);
    rowL1.setComponentId('row1L' + DVE.Utils.DveUtils.generateUiID());

    colOf.setHtmSelector(DVE.Core.Plugin.Constants.COL);
    colOf.setComponentId('colOf-' + rowL1.getComponentId());
    colOf.setClasses(DVE.Core.Plugin.Constants.colMd12);
    rowL1.AddComponent(colOf);

    this.DVEContainer.AddComponent(rowL1);
  }






  createOneLineTowColumn(): void {
    let rowL2 = new DVE.Core.Definitions.Container();
    rowL2.setHtmSelector(DVE.Core.Plugin.Constants.ROW);
    rowL2.setComponentId('row2L' + DVE.Utils.DveUtils.generateUiID());

    let colOf = new DVE.Core.Definitions.Container();
    let col2Of = new DVE.Core.Definitions.Container();

    colOf.setHtmSelector(DVE.Core.Plugin.Constants.COL);
    colOf.setComponentId('col1Of-' + rowL2.getComponentId());
    colOf.setClasses(DVE.Core.Plugin.Constants.colMd6);

    col2Of.setHtmSelector(DVE.Core.Plugin.Constants.COL);
    col2Of.setComponentId('col2Of-' + rowL2.getComponentId());
    col2Of.setClasses(DVE.Core.Plugin.Constants.colMd6);
    rowL2.AddComponent(colOf);
    rowL2.AddComponent(col2Of);
    this.DVEContainer.AddComponent(rowL2);
  }
  createOneLineThreeColumn(): void {
    let rowL3 = new DVE.Core.Definitions.Container();
    rowL3.setHtmSelector(DVE.Core.Plugin.Constants.ROW);
    rowL3.setComponentId('row3L' + DVE.Utils.DveUtils.generateUiID());

    let colOf = new DVE.Core.Definitions.Container();
    let col2Of = new DVE.Core.Definitions.Container();
    let col3Of = new DVE.Core.Definitions.Container();

    colOf.setHtmSelector(DVE.Core.Plugin.Constants.COL);
    colOf.setComponentId('col1Of-' + rowL3.getComponentId());
    colOf.setClasses(DVE.Core.Plugin.Constants.colMd4);

    col2Of.setHtmSelector(DVE.Core.Plugin.Constants.COL);
    col2Of.setComponentId('col2Of-' + rowL3.getComponentId());
    col2Of.setClasses(DVE.Core.Plugin.Constants.colMd4);

    col3Of.setHtmSelector(DVE.Core.Plugin.Constants.COL);
    col3Of.setComponentId('col3Of-' + rowL3.getComponentId());
    col3Of.setClasses(DVE.Core.Plugin.Constants.colMd4);

    rowL3.AddComponent(colOf);
    rowL3.AddComponent(col2Of);
    rowL3.AddComponent(col3Of);

    this.DVEContainer.AddComponent(rowL3);




  }
  createOneLineFourColumn(): void {
    let rowL4 = new DVE.Core.Definitions.Container();
    rowL4.setHtmSelector(DVE.Core.Plugin.Constants.ROW);
    rowL4.setComponentId('row4L' + DVE.Utils.DveUtils.generateUiID());

    let colOf = new DVE.Core.Definitions.Container();
    let col2Of = new DVE.Core.Definitions.Container();
    let col3Of = new DVE.Core.Definitions.Container();
    let col4Of = new DVE.Core.Definitions.Container();

    colOf.setHtmSelector(DVE.Core.Plugin.Constants.COL);
    colOf.setComponentId('col1Of-' + rowL4.getComponentId());
    colOf.setClasses(DVE.Core.Plugin.Constants.colMd3);

    col2Of.setHtmSelector(DVE.Core.Plugin.Constants.COL);
    col2Of.setComponentId('col2Of-' + rowL4.getComponentId());
    col2Of.setClasses(DVE.Core.Plugin.Constants.colMd3);

    col3Of.setHtmSelector(DVE.Core.Plugin.Constants.COL);
    col3Of.setComponentId('col3Of-' + rowL4.getComponentId());
    col3Of.setClasses(DVE.Core.Plugin.Constants.colMd3);

    col4Of.setHtmSelector(DVE.Core.Plugin.Constants.COL);
    col4Of.setComponentId('col4Of-' + rowL4.getComponentId());
    col4Of.setClasses(DVE.Core.Plugin.Constants.colMd3);

    rowL4.AddComponent(colOf);
    rowL4.AddComponent(col2Of);
    rowL4.AddComponent(col3Of);
    rowL4.AddComponent(col4Of);

    this.DVEContainer.AddComponent(rowL4);

  }


  public createText(model: DVE.Core.Definitions.Container): void {
    let textModel = new DVE.Core.Plugin.Text();
    if (model.getComponents().length < 1) {

      //console.log(model);
      textModel.setComponentId('text-node-of-' + model.getComponentId());
      textModel.setClasses('textElement');
      textModel.setHtmSelector('textarea');
      model.AddComponent(textModel);
      //console.log(model);
    } else {
      this.removeElements(model);
      textModel.setComponentId('text-node-of-' + model.getComponentId());
      textModel.setClasses('textElement');
      textModel.setHtmSelector('textarea');
      model.AddComponent(textModel);

    }






  }
  public createImage(model: DVE.Core.Definitions.Container): void {
    let imageModel = new DVE.Core.Plugin.Image();
    if (model.getComponents().length < 1) {

      imageModel.setComponentId('image-node-of-' + model.getComponentId());
      imageModel.setClasses('imageClass');
      imageModel.setHtmSelector('img');
      imageModel.setHref('');
      model.AddComponent(imageModel);
    } else {
      this.removeElements(model);

      imageModel.setComponentId('image-node-of-' + model.getComponentId());
      imageModel.setClasses('imageClass');
      imageModel.setHtmSelector('img');
      model.AddComponent(imageModel);
    }
  }

  public createVideo(model: DVE.Core.Definitions.Container): void {
    let videoModel = new DVE.Core.Plugin.Video();
    if (model.getComponents().length < 1) {

      videoModel.setComponentId('video-node-of' + model.getComponentId());
      videoModel.setHtmSelector('video');
      videoModel.setHref('');
      model.AddComponent(videoModel);
    } else {
      this.removeElements(model);
      videoModel.setComponentId('video-node-of' + model.getComponentId());
      videoModel.setHtmSelector('video');
      model.AddComponent(videoModel);

    }
  }

  public renderImage(modelId: DVE.Core.Plugin.Image): void {
    console.log(this.bosta.imagem);
    modelId.setHref(this.bosta.imagem);
  }

  public showVideo(modelId: DVE.Core.Plugin.Video) {
    modelId.setHref(modelId.getHref().replace("watch?v=", "v/"));
  }
  private change(modelId): void {

  }


  public renderVideo(): void {

  }


  public removeElements(model: DVE.Core.Definitions.Container) {
    model.removeComponents();
  }

  public removeRow(rowId) {


  }

  saveContent(): void {
    console.log(JSON.stringify(this.DVEContainer));
    alert(JSON.stringify(this.DVEContainer));

  }


  /*public preview() {
    let content = document.getElementById('content-into-page');
    window.open();
  }*/

  public destroy() {
    this.DVEContainer = new DVE.Core.Definitions.Container();
    this.DVEContainer.setHtmSelector('row');
  }



  public watcher(type, param): void {
    let fetch, Zone;
    switch (type) {
      case 'btn-col':



        break;
      case 'btn-create':
        console.log(param);
        break;
      default: console.log(param);
        break;
    }
  }



}

自举(OptionMenu);

答案 1 :(得分:0)

你不应该这样做。你知道angular使用虚拟DOM吗? DOM树上的所有更改都需要通过特殊的API来完成,请参阅ElementRef。为什么你没有把所有的代码都放到html模板中,而是在组件里面创建它?