简体   繁体   中英

getElementById works only the first time

I'm using Ionic 2 and trying to use getElementbyId on

 <ion-content padding>    
   <ion-list id="list"></ion-list>    
 </ion-content>

so that i can add items the following way:

var listIon=document.getElementById("list");    
var li = document.createElement("ion-item");    
li.innerText=usern+": "+mensaje;    
var p = document.createElement("p");    
p.appendChild(li);    
listIon.appendChild(p);

It works perfectly fine the first time, but if I exit the page and reopen it I get an error saying that

cannot read property appendChild on null

. I have already read other questions where they say that the script is not at the bottom. By taking in count that in Ionic you don't put the script in the html at all I don't know what could be causing this.

Edit

I have uploaded the files here main problem is in chat-details, chat-details is opened from chat.

What exactly are you trying to do? I think you're thinking in an old Jquery way , but Ionic works on top of Angular2, so things are done in a different way.

I assume you want to append a new item to a list, which can be done by using *ngFor and an array of data. Or if you want to show a message under certain conditions, you can accomplish that by using *ngIf. You should try to avoid referencing the DOM directly, and update the component code instead to change the data shown in the view.

I've created this demo plunker just to show you how to do these things in a Angular2 way . Please let me know what would be the expected result, so I can update the plunker accordingly.

Component code:

@Component({
  selector: 'page-home',
  templateUrl: 'app/home.page.html'
})
export class HomePage {

  private count: number;
  public users: Array<string>;

  public showMessage: boolean;
  public message: string;

  constructor() {
    this.count = 1;
    this.users = [];

    this.showMessage = false;
    this.message = 'This is a secret message!';
  }

  public addUser(): void {
    this.users.push(`User ${this.count++}`);
  }

  public toggleMessage(): void {
    this.showMessage = !this.showMessage;
  }

}

View code:

<ion-header>
  <ion-navbar>
    <ion-title>HomePage</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Users</h2>
  <p *ngIf="showMessage">{{ message }}</p>
  <ion-list *ngFor="let user of users">
    <ion-item>
      <p>{{ user }}</p>
    </ion-item>
  </ion-list>
  <button ion-button (click)="addUser()">Add a user</button>
  <button ion-button (click)="toggleMessage()">Togle message</button>

</ion-content>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM