在指令中通过renderer2在textarea中添加了一个按钮,但它在浏览器中不可见,但我可以在控制台中看到它

时间:2018-06-07 06:36:45

标签: angular angular-renderer2

我正在尝试通过renderer2在指令中动态地向textarea添加一个按钮。但按钮不可见。以下是我的指令代码 -

@Directive({
  selector: '[appMain]'
})
export class MainDirective {
  @Input() initial: string; inText: string;
  constructor(private el : ElementRef, private rend: Renderer2) {
    let r= this.rend.createElement('button');
    let t= this.rend.createText('Click Me!');
    this.rend.appendChild(r, t);
    this.rend.appendChild(this.el.nativeElement,r);
    this.rend.setStyle(r, 'display', 'block');
    console.log(this.el.nativeElement);  

   }

当我控制台登录nativeElement时,该按钮可见。snapshot of console.log

1 个答案:

答案 0 :(得分:0)

可能想要添加到原生元素

let csrfcookie = function() {  // for django csrf protection
            let cookieValue = null,
                name = "csrftoken";
            if (document.cookie && document.cookie !== "") {
                let cookies = document.cookie.split(";");
                for (let i = 0; i < cookies.length; i++) {
                    let cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) == (name + "=")) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
};

$.ajax({
       type: "POST",
       beforeSend: function(request, settings) {
                    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                        request.setRequestHeader("X-CSRFToken", csrfcookie());
                    }
},

.... /// other codes