猿问

无法在 Angular 中将 mySQL 数据库条目文本“\n”转换为“<br>”?

我可以从数据库中将数据读取到我的角度应用程序,但我只是在文本中得到静态\n而不是新行。我知道我应该将所有\n出现的情况转换为<br />但我未能做到这一点,即使使用echo nl2br;


//extract from my php file

if($result = mysqli_query($con, $sql))   

{


  $animals = [];

  $cr = 0;

  while($row = mysqli_fetch_assoc($result))

  {


    $animals[$cr]['animal']  = $row['animal'];

    $animals[$cr]['t1'] = $row['title1'];

    $animals[$cr]['p1'] = $row['paragraph1'];

    $cr++;


}

echo nl2br($animals);

  echo json_encode($animals);

下面是我的角度文件


//extract from my animals.component.html file


    <div class="container" *ngFor="let animal of this.animals">


        {{animal.t1}}

        {{animal.p1}}

        {{animal.t2}}


    </div>

但是,我在网页上的输出(来自animal.t1)与数据库条目的文本完全相同:


Animals \n are \n fun \n .


我尝试了许多不同的方法,但似乎无法将\n's 转换为<br>. 有人对此有什么建议吗?


人到中年有点甜
浏览 122回答 2
2回答

侃侃尔雅

nl2br接受一个字符串而不是一个数组。如果您在查询中选择列,那就容易得多。只需映射行数组:  // SELECT animal, t1, p1 FROM table WHERE .....  while($row = mysqli_fetch_assoc($result))  {      $animals[] = array_map('nl2br', $row);  }  echo json_encode($animals);

慕后森

用途nl2br:$animals[$cr]['t1']&nbsp;=&nbsp;nl2br($row['title1']);
随时随地看视频慕课网APP
我要回答